我正在尝试使用 Roslyn 执行用户在运行时定义的 C# 代码,类似于此示例:
public class Globals
{
public int X;
public int Y;
}
var globals = new Globals { X = 1, Y = 2 };
Console.WriteLine(await CSharpScript.EvaluateAsync<int>("X+Y", globals: globals));
我的问题是脚本中使用的变量名在编译时是未知的。换句话说,我不知道我的全局类应该使用什么成员名称以及会有多少成员(脚本参数)。
我尝试使用 ExpandoObject 来解决问题,但无法使其正常工作。ExpandoObject 应该在这种情况下工作吗?还有其他方法可以解决问题吗?
更新
对于我的用例,最好的解决方案可能是使用System.Linq.Dynamic
:
//Expression typed in by the user at runtime
string Exp = @"A + B > C";
//The number of variables and their names are given elsewhere,
//so the parameter-array doesn't need to be hardcoded like in this example.
var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[]
{
Expression.Parameter(typeof(double), "A"),
Expression.Parameter(typeof(double), "B"),
Expression.Parameter(typeof(double), "C")
},
null, Exp);
var Lambda = e.Compile();
//Fake some updates...
foreach (var i in Enumerable.Range(0,10))
{
Console.WriteLine(Lambda.DynamicInvoke(i, 3, 10));
}