开发者

Using methods of an object without casting

开发者 https://www.devze.com 2023-02-05 04:03 出处:网络
I have a problem with casting/types and so on. Firstly, my query is a follow on from another post here:

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消