[英]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 首先,我的查询是此处另一篇文章的后续文章: 从System.Type初始化通用对象
so to continue on from this question, how can I use the methods of my newly created object? 因此,从这个问题继续讲,如何使用新创建的对象的方法?
ie 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 way, although I am using this application for WCF, this is not a WCF problem 顺便说一句,尽管我正在将此应用程序用于WCF,但这不是WCF问题
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.