【问题标题】:Using methods of an object without casting使用对象的方法而不进行强制转换
【发布时间】:2011-01-14 10:40:08
【问题描述】:

我在转换/类型等方面遇到问题。

首先,我的查询是此处另一篇文章的后续内容: Initialize generic object from a System.Type

那么继续这个问题,我该如何使用我新创建的对象的方法?

即我想做的如下:

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 问题

【问题讨论】:

    标签: c# reflection types casting generics


    【解决方案1】:

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

    【讨论】:

    • 很高兴我能提供答案! (眨眼;)
    【解决方案2】:

    没有动态对象:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2011-12-16
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      相关资源
      最近更新 更多