2011-01-14 43 views
0

我有鑄造/類型等問題。使用對象的方法而不需要鑄造

首先,我的查詢是從這裏另一篇文章一個遵循: 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問題

回答

2

使用dynamic object試試?這使您可以調用可能存在或可能不存在的方法。

+0

太簡單的人,非常感謝。 – Shane 2011-01-14 10:45:02

+0

很高興我能提供一個答案! (眨眼睛;) – 2011-01-14 10:46:41

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;