如何在C#中使用类型创建泛型委托? [英] How do I make a generic delegate using a type in C#?

查看:44
本文介绍了如何在C#中使用类型创建泛型委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有类型,例如:

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.

并应执行以下操作:

myDict[myType][i] (objectOfMyType);

任何建议将不胜感激.

谢谢!

推荐答案

如您所料,您不能直接在字典中使用 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});

这篇关于如何在C#中使用类型创建泛型委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆