将自定义委托类型转换为Action <object> </object>

时间:2014-01-04 17:51:14

标签: c# reflection delegates

我想将下面的委托类型转换为Action类型,但我收到运行时错误

internal delegate void ExecuteMenuClick(object Sender);

使用反射我得到的方法的MethodInfo具有相同的参数。

void SampleMethod(object Sender){}

现在,我有一个命令类实现,它将Action作为参数。我想创建一个委托并将其传递给命令类,以便调用它。

CommandExecutor loclCommand = new CommandExecutor((Action<object>)Delegate.CreateDelegate(typeof(ExecuteMenuClick), instance, methodinfo);

然而,我最终收到以下错误

Unable to cast object of type 'sampleproject.ExecuteMenuClick' to type 'System.Action`1[System.Object]'.

1 个答案:

答案 0 :(得分:1)

您在Delegate.CreateDelegate的调用中传递了错误的委托类型。您应该使用以下代码,它会传递typeof(Action<object>),从而产生正确类型的委托。

CommandExecutor loclCommand = new CommandExecutor((Action<object>)Delegate.CreateDelegate(typeof(Action<object>), instance, methodinfo);
相关问题