1.使用
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
2.定义 RoslynHelper 类, 添加一个 DataTable GetTableBySql(string sql = "") 方法
3. 先定义 待执行的 C# 脚本方法
比如执行一个sql语句, 得到查询的结果集 DataTable
==>去动态执行 Common.RoslynHelper().GetTableBySql(sql) 方法
string = @"
using System;
using YXTASK.Common;
public class ScriptedClass
{
public System.Data.DataTable DataRes { get; set; }
public ScriptedClass()
{
string sql= "" select * from (select id,age.name from StudentInfo) where age<=20"";
this.DataRes = new Common.RoslynHelper().GetTableBySql(sql);
}
}
";
4.调用
1>传入需要注入的命名空间
var scriptOptions = ScriptOptions.Default.AddReferences(typeof(System.Data.DataTable).Assembly, typeof(RoslynHelper).Assembly);
2>传入待执行的C# 文本
var script1 = CSharpScript.RunAsync(code1, scriptOptions).Result;
3>执行脚本
var result1 = script1.ContinueWithAsync<System.Data.DataTable>("new ScriptedClass().DataRes").Result;
4>得到返回值
DataTable res = result1.ReturnValue;
try { var scriptOptions = ScriptOptions.Default.AddReferences(typeof(System.Data.DataTable).Assembly, typeof(RoslynHelper).Assembly); var script1 = CSharpScript.RunAsync(code1, scriptOptions).Result; var result1 = script1.ContinueWithAsync<System.Data.DataTable>("new ScriptedClass().DataRes").Result; res = result1.ReturnValue; Console.WriteLine(res.Rows.Count); Console.WriteLine(""); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.WriteLine(""); }
标签:core,Console,C#,sql,RoslynHelper,WriteLine,3.1,var,DataTable From: https://www.cnblogs.com/mjxxsc/p/17266477.html