【问题标题】:How do I make a generic delegate using a type in C#?如何使用 C# 中的类型创建泛型委托?
【发布时间】:2012-12-05 16:39:49
【问题描述】:

如果我有一个类型,比如:

Type type = myObject.GetType ();

如何创建一个使用该类型对象作为参数的通用委托?我希望代码类似于:

myDelegate = Action<type> (type parameter);

上面的代码显然不会也不能按原样工作,但我怎样才能让它工作呢?我什至可以让它工作吗?

最终,我有一个 Dictionary > 的字典,其中包含一个类型和一个委托列表,这些委托应该将该类型的对象作为参数。

并且应该像这样执行:

myDict[myType][i] (objectOfMyType);

任何建议将不胜感激。

谢谢!

【问题讨论】:

  • 泛型不需要知道它们使用的是什么类型。这就是使它们通用的原因。
  • 也许这会有所帮助:stackoverflow.com/questions/773099/…
  • 一个真实的例子会有所帮助

标签: c# types delegates unity3d


【解决方案1】:

如您所料,您不能直接在字典中使用Action&lt;&gt; 类型的实例化。您必须将其输入到System.Delegate,然后使用DynamicInvoke

Dictionary<Type, List<Delegate>> dict;

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

首先要创建委托,请使用反射:

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

【讨论】:

  • 谢谢,效果很好!我只使用了最上面的代码块,这让我走上了正确的道路,再见样板演员!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多