How do I make a generic delegate using a type in C#?

江枫思渺然 提交于 2021-01-28 05:11:12

问题


If I have a type, like:

Type type = myObject.GetType ();

How do I make a generic delegate that uses objects of that that type as a parameter? I would expect code something like:

myDelegate = Action<type> (type parameter);

The above code obviously won't and doesn't work as is, but how can I make it work? Can I even make it work?

Ultimately, I have a dictionary of Dictionary < Type, List < Action < > >, which holds a type and a list of delegates that should take an object of that type as parameter.

And should be executed something like this:

myDict[myType][i] (objectOfMyType);

Any suggestions would be greatly appreciated.

Thanks!


回答1:


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});


来源:https://stackoverflow.com/questions/13933565/how-do-i-make-a-generic-delegate-using-a-type-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!