使用变量名称调用接口

use*_*714 2 c# wcf interface

我在变量中分配接口名称,通过该变量,我需要调用接口,即在ChannelFactory类中只接受接口.如果我在ChannelFactory中直接将接口指定为Test,那么它工作正常.

 string interfaceName = "Test";
 var factory = new ChannelFactory<**interfaceName**>(new BasicHttpBinding(), new EndpointAddress(*********));
Run Code Online (Sandbox Code Playgroud)

请建议可能的方式,如何从字符串变量到接口进行类型转换.

Wou*_*ort 5

您不能直接从字符串变量类型转换为接口.但是,您可以使用反射来创建泛型类型.

但请注意,生成的工厂将是object类型,因此调用其上的所有接口方法也必须通过反射(或使用dynamic关键字)完成

下面的代码将创建ChannelFactory槽反射,但正如您所看到的结果是object类型,这意味着您无法直接在其上调用通道方法.

string interfaceName = "StackOverflow.ITest";

Type f = typeof (ChannelFactory<>);
Type[] typeargs = {Type.GetType(interfaceName, true)};

Type constructed = f.MakeGenericType(typeargs);
object factory = Activator.CreateInstance(constructed);
Run Code Online (Sandbox Code Playgroud)