MethodInfo オブジェクトからアクション デリゲートを取得したいと考えています。これは可能ですか?
15244 次
2 に答える
73
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);
などについては、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);
于 2010-06-11T09:14:16.220 に答える
1
これはジョンのアドバイスの上でもうまくいくようです:
public static class GenericDelegateFactory
{
public static object CreateDelegateByParameter(Type parameterType, object target, MethodInfo method) {
var createDelegate = typeof(GenericDelegateFactory).GetMethod("CreateDelegate")
.MakeGenericMethod(parameterType);
var del = createDelegate.Invoke(null, new object[] { target, method });
return del;
}
public static Action<TEvent> CreateDelegate<TEvent>(object target, MethodInfo method)
{
var del = (Action<TEvent>)Delegate.CreateDelegate(typeof(Action<TEvent>), target, method);
return del;
}
}
于 2012-06-17T17:09:11.073 に答える