我如何将操作员分配给代表?int a = 5;int b = 2;Func<int, int, int> operation = /* int.operator+ or int.operator- */;int result = operation(a, b);我知道三种方法:Func<int, int, int> operation = (a, b) => a + b;这一个包装成一个额外的函数调用。Func<C, C, C> operation = (Func<C, C, C>)typeof(C).GetMethod("op_Addition").CreateDelegate(typeof(Func<C, C, C>));这个很可怕,不适用于基元。Expression<Func<C, C, C>> expression = (c, c2) => c + c2;BinaryExpression binaryExpression = (BinaryExpression)expression.Body;MethodInfo binaryExpressionMethod = binaryExpression.Method;Func<C, C, C> operation = (Func<C, C, C>)binaryExpressionMethod.CreateDelegate(typeof(Func<C, C, C>));这个更可怕,也不适用于基元。有优雅的方法吗?
1 回答
达令说
TA贡献1821条经验 获得超6个赞
您可以使用.Compilelambda 表达式的方法执行此操作:
Func<int, int, int> result;
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var body = Expression.Add(a, b);
var lambda = Expression.Lambda<Func<int, int, int>>(body, a, b);
现在你lambda已经a + b准备好编译了:
result = lambda.Compile();
Console.WriteLine(result(5, 2)); // print 7
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消