2011-09-19 75 views
0

我有List<Type>,这里Type是我使用反射的界面。 那么如何在这些Type上使用channnel工厂创建wcf代理。在System.Type上创建动态代理

,如:

foreach(Type t in types) 
{ 
t proxy = ChannelFactory<t>.CreateChannel(new NetTcpBinding(), 
      new EndpointAddress(serviceAddress)); 
} 

这里t是接口,但上面的代码是给编译器error.Can有人告诉我如何在类型创建WCF服务代理。

回答

3

您可以使用反射和调用方法Type.MakeGenericType

foreach (Type t in types) 
{ 
    Type genType = typeof(ChannelFactory<>).MakeGenericType(t); 

    MethodInfo createChannelMethod = genType.GetMethod("CreateChannel", 
             new[] { typeof(Binding), 
               typeof(EndpointAddress) }); 

    var proxy = createChannelMethod.Invoke(
           null, 
           BindingFlags.Static, 
           null, 
           new object[] { 
            new NetTcpBinding(), 
            new EndpointAddress(serviceAddress) 
           }, 
           null); 
} 
+0

THX使用上面的代码即时得到编译器错误为“找到隐式类型的数组没有最好类型的”快速reply.While。 – Geeta

+0

我已更新我的答案。只需写入'new object []'而不是'new []' – Jan

+0

通过将它作为新对象[] {new NetTcpBinding(),new EndpointAddress(serviceAddress)} – Geeta