是否可以在 C# 中从字符串创建匿名方法?
例如如果我有一个字符串 "x + y * z"
是否可以将其转换为某种方法/lambda 对象,我可以用任意 x
,y
,z
参数?
最佳答案
这是可能的,是的。您必须解析字符串,例如,使用表达式树编译委托(delegate)。
下面是一个使用表达式树创建 (x, y, z) => x + y * z
的例子:
ParameterExpression parameterX = Expression.Parameter(typeof(int), "x");
ParameterExpression parameterY = Expression.Parameter(typeof(int), "y");
ParameterExpression parameterZ = Expression.Parameter(typeof(int), "z");
Expression multiplyYZ = Expression.Multiply(parameterY, parameterZ);
Expression addXMultiplyYZ = Expression.Add(parameterX, multiplyYZ);
Func<int,int,int,int> f = Expression.Lambda<Func<int, int, int, int>>
(
addXMultiplyYZ,
parameterX,
parameterY,
parameterZ
).Compile();
Console.WriteLine(f(24, 6, 3)); // prints 42 to the console
关于c# - 在 C# 中从字符串创建匿名方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1574845/