C# 如何将方法组强制转换为对象&引用;无法转换方法组';XXX和x27;非委托类型';对象'&引用;

C# 如何将方法组强制转换为对象&引用;无法转换方法组';XXX和x27;非委托类型';对象'&引用;,c#,C#,有时,我会遇到需要在不知道其类型的情况下执行泛型方法的问题 我知道每次使用反射都可以做到这一点,但我正在尝试编写一个助手方法: public static object InvokeGeneric<T>(this T @this, Expression<Func<T, object>> method, Type genericType, params object[] arguments) { // I think I k

有时,我会遇到需要在不知道其类型的情况下执行泛型方法的问题

我知道每次使用反射都可以做到这一点,但我正在尝试编写一个助手方法:

public static object InvokeGeneric<T>(this T @this, 
    Expression<Func<T, object>> method, 
    Type genericType, 
    params object[] arguments)
{
    // I think I know what to do here
    // look at the expression tree, grab 
    // the method info, do the 
    // reflection in here, etc.
    return null;
}
publicstaticobjectinvokegeneric(thistt@this,
表达方法,
类型genericType,
参数对象[]参数)
{
//我想我知道该怎么做了
//看表达式树,抓住
//方法信息,请执行以下操作:
//这里的倒影等等。
返回null;
}
这样我就可以做到:

this._myService.InvokeGeneric(
    e => e.MyGenericMethod, // interface IMyService { void MyGenericMethod<T>(T t); }
    typeof(MyGenericType),
    myArg);
this.\u myService.InvokeGeneric(
e=>e.MyGenericMethod,//接口IMyService{void MyGenericMethod(T);}
类型(MyGenericType),
myArg);
但是,我遇到此错误:无法将方法组“XXX”转换为非委托类型“object”

在不更改调用语法的情况下,如何更改助手方法的方法签名以执行所需操作?

编辑:

我把它归结为:

this._myService.InvokeGeneric<IMyService, object, MyArgType>(e => e.MyGenericMethod, typeof(MyGenericType), myArg);
this.\u myService.InvokeGeneric(e=>e.MyGenericMethod,typeof(MyGenericType),myArg);
缺点(除了额外的键入之外)是,对于希望支持的
Func
Action
的每个泛型变体,都需要重载

public static object InvokeGeneric<T, T1>(this object @this, Expression<Func<T, Action<T1>>> method, Type genericType, params object[] arguments)
{ }    

public static object InvokeGeneric<T, T1, T2>(this object @this, Expression<Func<T, Action<T1, T2>>> method, Type genericType, params object[] arguments)
{ }
public static object InvokeGeneric(this object@this,Expression method,Type genericType,params object[]参数)
{ }    
公共静态对象InvokeGeneric(this对象@this,表达式方法,类型genericType,参数对象[]参数)
{ }

等等,我将使用这个解决方案,但是如果有人有符合更简洁语法的东西,请告诉我,我会接受它。阅读了一些关于方法组的内容后,我意识到我的语法是不明确的,如果有重载的话,这可能意味着像这样的强类型语法可能会更好。

应该是
e=>e.MyGenericMethod()
?当你正常地搜索错误消息时,谷歌会弹出这样的消息,但不会,我不想忽略那种方法的结果;我想将该方法传入
InvokeGeneric
。也就是说,我可以用伪参数调用该方法并忽略它们,然后只获取方法信息,这就是您要做的,但这可能需要大量的键入。我认为这种语法最简洁。您不能将方法分配给对象,但可以改为执行
Action=e.MyGenericMethod
。不过,这并不是一个要求的解决方案。@AlexD请参阅我的编辑;我不知道你是不是这个意思。但这正是我要做的。感谢您的回复。@WordsLekejared我的意思是用适当的
操作替换
表达式中的
对象
,以消除“无法转换方法组…”错误。这和你做的差不多。但是我没有发现一种方法可以在不改变来电方的情况下让事情顺利进行。