C# 使用对象的方法而不进行铸造

C# 使用对象的方法而不进行铸造,c#,reflection,types,casting,generics,C#,Reflection,Types,Casting,Generics,我在铸造/类型等方面有问题 首先,我的问题是另一篇文章的后续: 那么从这个问题继续下去,我如何使用我新创建的对象的方法呢 i、 e.我想做的事情如下: Type iFace = typeof(IService1); Type genericListType = typeof(System.ServiceModel.ChannelFactory<>).MakeGenericType(iFace); object factory = Activator.CreateInstance(g

我在铸造/类型等方面有问题

首先,我的问题是另一篇文章的后续:

那么从这个问题继续下去,我如何使用我新创建的对象的方法呢

i、 e.我想做的事情如下:

Type iFace = typeof(IService1);
Type genericListType = typeof(System.ServiceModel.ChannelFactory<>).MakeGenericType(iFace);
object factory = Activator.CreateInstance(genericListType, new object[]
                    {
                        new BasicHttpBinding(),
                        new EndpointAddress("http://localhost:1693/Service.svc")
                    });
var channel = factory.CreateChannel();

顺便说一句,虽然我正在使用这个应用程序进行WCF,但这不是一个WCF问题

请尝试使用?这允许您调用可能存在或不存在的方法。

尝试使用?这允许您调用可能存在或不存在的方法。

没有动态对象:

object factory = Activator.CreateInstance(genericListType, new object[]
{
    new BasicHttpBinding(),
    new EndpointAddress("http://localhost:1693/Service.svc")
});

Type factoryType = factory.GetType();
MethodInfo methodInfo = factoryType.GetMethod("CreateChannel");
var channel = methodInfo.Invoke(factory) as YourChannelType;

没有动态对象:

object factory = Activator.CreateInstance(genericListType, new object[]
{
    new BasicHttpBinding(),
    new EndpointAddress("http://localhost:1693/Service.svc")
});

Type factoryType = factory.GetType();
MethodInfo methodInfo = factoryType.GetMethod("CreateChannel");
var channel = methodInfo.Invoke(factory) as YourChannelType;

很高兴我能提供答案!眨眼;很高兴我能提供答案!眨眼;