繁体   English   中英

为模板动态创建泛型类型

[英]Dynamically Create a generic type for template

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

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

就我而言,我正在做路由,所以我不知道我的通道工厂将使用什么类型。 我可以解析一条消息 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);

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

你应该看看 Ayende 的这篇文章: WCF、Mocking 和 IoC:哦,天哪! . 靠近底部的某个地方是一个名为 GetCreationDelegate 的方法,它应该会有所帮助。 它基本上是这样做的:

string typeName = ...;
Type proxyType = Type.GetType(typeName);

Type type = typeof (ChannelFactory<>).MakeGenericType(proxyType);

object target = Activator.CreateInstance(type);

MethodInfo methodInfo = type.GetMethod("CreateChannel", new Type[] {});

return methodInfo.Invoke(target, new object[0]);

need to create a channel with the exact contract type in your specific case?这里有一个问题:您需要在您的特定情况下创建一个具有确切合同类型的频道吗?

由于您正在进行布线,因此很有可能您可以简单地处理通用通道形状。 例如,如果您正在路由单向消息,那么您可以创建一个通道来发送消息,如下所示:

ChannelFactory<IOutputChannel> factory = new ChannelFactory<IOutputChannel>(binding, endpoint);
IOutputChannel channel = factory.CreateChannel();
...
channel.SendMessage(myRawMessage);

如果您需要发送到双向服务,只需使用 IRequestChannel 代替。

如果您正在进行路由,通常只处理通用通道形状(与外部通用的包罗万象的服务合同)并确保您发送的消息正确无误会容易得多标题和属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM