如何从MethodInfo创建Action委托?

fra*_*nja 36 .net action methodinfo

我想从MethodInfo对象获取一个动作委托.这可能吗?

谢谢.

Jon*_*eet 63

使用Delegate.CreateDelegate:

// Static method
Action action = (Action) Delegate.CreateDelegate(typeof(Action), method);

// Instance method (on "target")
Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method);
Run Code Online (Sandbox Code Playgroud)

对于Action<T>等,只需在任何地方指定适当的委托类型.

在.NET Core中,Delegate.CreateDelegate不存在,但是MethodInfo.CreateDelegate:

// Static method
Action action = (Action) method.CreateDelegate(typeof(Action));

// Instance method (on "target")
Action action = (Action) method.CreateDelegate(typeof(Action), target);
Run Code Online (Sandbox Code Playgroud)