从类型名称动态创建委托
本文关键字:创建 动态 类型 | 更新日期: 2023-09-27 18:12:04
我想创建一个泛型委托,但我只在执行时知道类型。
这是我要创建的委托:
public delegate void MyDel<T>(T t,string msg);
这里是我要实例化的方法并使用委托
Type typeSet = set.GetType();
MethodInfo method = typeSet.GetMethod("Add");
Delegate test = Delegate.CreateDelegate(typeof(MyDel<typeSet>, method);
在编译时我不知道typeSet。不幸的是,我要调用的方法不是静态的
有人知道吗?
Thanks in advance
您需要使用MakeGenericType
:
Type template = typeof(MyDel<>);
Type specific = template.MakeGenericType(typeSet);
Delegate test = Delegate.CreateDelegate(specific, method);
我认为后就是你…