jpa*_*pa7 9 c# expression-trees
我是使用Expressions的新手,我收到以下错误:
System.ArgumentException:静态方法需要null实例,非静态方法需要非null实例.
参数名称:方法
代码如下:
int inP = 100;
object inParam = inP;
Type inParamType = inParam.GetType();
ParameterExpression pe = Expression.Parameter(typeof(S), "pe");
Expression left = Expression.Property(pe, typeof(S).GetProperty(propName));
Expression right = Expression.Constant(inParam, inParamType);
MethodInfo mi = inParamType.GetMethod(operand, BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(object) }, null);
Expression e1 = Expression.Call(mi, left, right);
Run Code Online (Sandbox Code Playgroud)
小智 7
你正在使用BindingFlags.Instance
,所以你只会得到实例方法.实例方法必须作为C#调用a.f(b)
,而不是f(a, b)
,并且转换为表达式树Expression.Call(left, mi, right)
,而不是Expression.Call(mi, left, right)
.这就是异常告诉你的:
静态方法需要null实例,非静态方法需要非null实例.
在这种情况下,您有一个非静态方法,因此您必须传入一个要调用该方法的实例.