gpt4 book ai didi

c# - 从类型名称动态创建委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 21:11:50 27 4
gpt4 key购买 nike

我想创建一个通用委托(delegate),但我只知道执行时的类型。

这是我要创建的委托(delegate):

public delegate void MyDel<T>(T t,string msg);

这是我要实例化和使用委托(delegate)的方法

Type typeSet = set.GetType();
MethodInfo method = typeSet.GetMethod("Add");
Delegate test = Delegate.CreateDelegate(typeof(MyDel<typeSet>, method);

我在编译时不知道 typeSet 在哪里。不幸的是,我想调用的方法不是静态的。

有人知道吗?

提前致谢

最佳答案

您需要使用 MakeGenericType 创建特定的委托(delegate)类型:

Type template = typeof(MyDel<>);
Type specific = template.MakeGenericType(typeSet);
Delegate test = Delegate.CreateDelegate(specific, method);

认为这就是你想要的......

关于c# - 从类型名称动态创建委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7835013/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com