Tôi muốn nhận được một đại biểu hành động từ một đối tượng MethodInfo. Điều này có thể không?Làm cách nào tôi có thể tạo một đại diện Hành động từ MethodInfo?
Cảm ơn bạn.
Tôi muốn nhận được một đại biểu hành động từ một đối tượng MethodInfo. Điều này có thể không?Làm cách nào tôi có thể tạo một đại diện Hành động từ MethodInfo?
Cảm ơn bạn.
Sử dụng 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);
Đối với một Action<T>
vv, chỉ cần xác định loại đại biểu thích hợp ở khắp mọi nơi.
Trong NET Core, Delegate.CreateDelegate
không tồn tại, nhưng MethodInfo.CreateDelegate
làm:
// Static method
Action action = (Action) method.CreateDelegate(typeof(Action));
// Instance method (on "target")
Action action = (Action) method.CreateDelegate(typeof(Action), target);
Điều này dường như làm việc trên lời khuyên của John quá:
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;
}
}
upvoted. Làm cách nào để áp dụng điều này cho DataEventArgs? http://stackoverflow.com/questions/33376326/how-to-create-generic-event-delegate-from-methodinfo –
'Delegate.CreateDelegate' dường như không có sẵn trong .Net Core. Có ý tưởng nào không? – IAbstract
@IAbstract: Thú vị - Tôi đã không phát hiện ra điều đó. Thay vào đó, bạn có thể gọi 'MethodInfo.CreateDelegate'. (Chỉ cần thử nó, và nó làm việc tốt.) –