简体   繁体   English

如何通过反射调用接受 Func<> 参数的方法?

[英]How to invoke with reflection a method that accepts a Func<> parameter?

When I try to add the Func<> parameter in the array of MethodInfo.Invoke , it's giving me the error that it can't convert a method group to an object.当我尝试在MethodInfo.Invoke的数组中添加Func<>参数时,它给我的错误是它无法将方法组转换为 object。

How do I deal with this?我该如何处理?

The method's signature:方法的签名:

static bool Something(Func<Expression, Expression, BinaryExpression> body)

What I'm passing:我正在传递的内容:

MethodInfo.Invoke(null, new object[] { Expression.Subtract }); // compilation error

CS0428 Cannot convert method group 'Subtract' to non-delegate type 'object'. CS0428 无法将方法组“减去”转换为非委托类型“对象”。 Did you intend to invoke the method?您是否打算调用该方法?

There is indeed no conversion from method groups to object , but there are conversions from method groups to compatible delegate types ( method group conversions ), and there are also conversions from delegate types to object .确实没有从方法组到object的转换,但是从方法组到兼容委托类型的转换( 方法组转换),也有从委托类型到object的转换。 So you can first convert the method group to Func<Expression, Expression, BinaryExpression> with a cast, then it can be implicitly converted to object :因此,您可以首先使用强制转换将方法组转换为Func<Expression, Expression, BinaryExpression> ,然后可以将其隐式转换为object

someMethodInfo.Invoke(null, new object[] { (Func<Expression, Expression, BinaryExpression>)Expression.Subtract });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM