gpt4 book ai didi

c# - 为模板动态创建通用类型

转载 作者:可可西里 更新时间:2023-11-01 07:50:00 28 4
gpt4 key购买 nike

我正在使用 ChannelFactory 对 WCF 进行编程,它需要一个类型才能调用 CreateChannel 方法。例如:

IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...);

在我的例子中,我正在做路由,所以我不知道我的 channel 工厂将使用什么类型。我可以解析消息 header 以确定类型,但我在那里碰壁了,因为即使我有 Type 的实例,我也无法在 ChannelFactory 需要通用类型的地方传递它。

另一种用非常简单的方式重申这个问题的方法是,我正在尝试做这样的事情:

string listtype = Console.ReadLine(); // say "System.Int32"
Type t = Type.GetType( listtype);
List<t> myIntegers = new List<>(); // does not compile, expects a "type"
List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time?

是否有我可以在 C# 中利用的方法?

最佳答案

你要找的是 MakeGenericType

string elementTypeName = Console.ReadLine();
Type elementType = Type.GetType(elementTypeName);
Type[] types = new Type[] { elementType };

Type listType = typeof(List<>);
Type genericType = listType.MakeGenericType(types);
IProxy proxy = (IProxy)Activator.CreateInstance(genericType);

因此,您正在做的是获取通用"template"类的类型定义,然后使用您的运行时驱动类型构建该类型的特化。

关于c# - 为模板动态创建通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67370/

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