您可以如下动态创建函数,
Expression<Func<int, int, string>> exp = (x, y) => (x + y).ToString();
var func = exp.Compile();
Console.WriteLine(func.Invoke(2, 3));
您也可以将它们放入字典并动态使用它们。
Expression<Func<int, int, string>> expSum = (x, y) => (x + y).ToString();
Expression<Func<int, int, string>> expMul = (x, y) => (x*y).ToString();
Expression<Func<int, int, string>> expSub = (x, y) => (x - y).ToString();
Dictionary<string, Expression<Func<int, int, string>>> myExpressions =
new Dictionary<string, Expression<Func<int, int, string>>>();
myExpressions.Add("summation", expSum);
myExpressions.Add("multiplication", expMul);
myExpressions.Add("subtraction", expSub);
foreach (var myExpression in myExpressions)
{
Console.WriteLine(myExpression.Value.Compile().Invoke(2, 3));
}