且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中使用类型创建泛型委托?

更新时间:2023-01-16 08:53:22

如您所料,您不能直接在字典中使用 Action<> 类型的实例化.您必须将其键入 System.Delegate ,然后使用 DynamicInvoke :

As you might expect, you can't use instantiations of the Action<> type directly in the dictionary. You'll have to type it to System.Delegate, and use DynamicInvoke:

Dictionary<Type, List<Delegate>> dict;

dict[myType][i].DynamicInvoke(objectOfMyType);

并首先使用反射创建委托:

and to create the delegates in the first place, use reflection:

Type delegateType = typeof(Action<>).MakeGenericType(myType);

MethodInfo delegatedMethod = typeof(ContainingType).GetMethod("MethodToInvoke");

Delegate myDelegate = Delegate.CreateDelegate(delegateType, delegatedMethod);
dict.Add(myType, new List<Delegate> {myDelegate});