C# 为什么“dynamicMethod.CreateDelegate(typeof(Action)).Method.Invoke(null,新对象[0]);”抛出异常?

C# 为什么“dynamicMethod.CreateDelegate(typeof(Action)).Method.Invoke(null,新对象[0]);”抛出异常?,c#,delegates,invoke,system.reflection,reflection.emit,C#,Delegates,Invoke,System.reflection,Reflection.emit,这似乎有效,提供了一种(奇怪的)调用操作的方法: Action action = () => { }; action.Method.Invoke(action.Target, new object[0]); var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action; action(); var action = dynamicMethod.CreateDelegate(typeof(Action)) as A

这似乎有效,提供了一种(奇怪的)调用
操作的方法:

Action action = () => { };
action.Method.Invoke(action.Target, new object[0]);
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action();
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action.Method.Invoke(action.Target, new object[0]);  // Throws exception
这似乎有效,为创建
操作提供了一种(有用的)方法:

Action action = () => { };
action.Method.Invoke(action.Target, new object[0]);
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action();
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action.Method.Invoke(action.Target, new object[0]);  // Throws exception
但是,这会引发
异常

Action action = () => { };
action.Method.Invoke(action.Target, new object[0]);
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action();
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action.Method.Invoke(action.Target, new object[0]);  // Throws exception
MethodInfo必须是运行时MethodInfo对象

问题:为什么上面的代码段会引发
异常


工作代码示例 这会导致
控制台
写入:

Exception thrown: 'System.ArgumentException' in mscorlib.dll
System.ArgumentException: MethodInfo must be a runtime MethodInfo object.
Parameter name: this
  at System.Reflection.Emit.DynamicMethod.RTDynamicMethod.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
  [...]

思想 我尝试了调用
action.Method.Invoke()
的一系列变体,但是调用参数的各种变体似乎都不会改变异常消息

MethodInfo必须是运行时MethodInfo对象


我的猜测是,
action.Method
不是一个“运行时MethodInfo”,尽管它是一个“MethodInfo”。不过,我不确定运行时-
MethodInfo
和非运行时-
MethodInfo
之间的区别是什么。

MethodInfo
是一种抽象类型,它有几个实现

其中之一是内部类型
System.Reflection.RuntimeMethodInfo
。这是反映现有运行时类型的方法时得到的结果:

Console.WriteLine(typeof(object).GetMethod("ToString").GetType().FullName); // System.Reflection.RuntimeMethodInfo
另一方面,
DynamicMethod.CreateDelegate
使用了
MethodInfo
的另一个实现:

Console.WriteLine(action.Method.GetType().FullName); // System.Reflection.Emit.DynamicMethod+RTDynamicMethod
而且它似乎不支持通过
MethodInfo.Invoke
调用

但是,如果由于某种原因无法使用所创建委托的
Invoke
方法(例如,因为您不知道确切的委托类型),您仍然可以使用
delegate.DynamicInvoke
方法(但是,委托的动态调用几乎与反射API一样慢):


您不需要创建一个类型并从中获取方法信息吗?比如?@约翰,我还没测试过,但那可能有用吗?我的意思是,这是一种我有解决办法的情况,所以我并不需要解决方案,我只是想弄清楚为什么这种方法会意外失败。