我正在使用ChannelFactory编写WCF,它需要一个类型来调用CreateChannel方法.例如:
IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...);
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我正在做路由,所以我不知道我的渠道工厂将使用什么类型.我可以解析一个消息头来确定类型,但我在那里碰到了一堵砖墙,因为即使我有一个Type I实例也无法传递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?
Run Code Online (Sandbox Code Playgroud)
我可以在C#中使用这种方法吗?
IDi*_*ble 29
您正在寻找的是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);
Run Code Online (Sandbox Code Playgroud)
所以你要做的是获取通用"模板"类的类型定义,然后使用运行时驱动类型构建类型的特化.
你应该看一下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]);
Run Code Online (Sandbox Code Playgroud)