Using methods of an object without casting
I have a problem with casting/types and so on.
Firstly, my query is a follow on from another post here: Initialize generic object from a System.Type
so to continue on from this question, how can I use the methods of my newly created object?
i.e. what I want to do is as follows:
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();
by the wa开发者_如何学运维y, although I am using this application for WCF, this is not a WCF problem
Try using a dynamic object? This allows you to call methods that might or might not exist.
Without dynamic objects:
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;
精彩评论