加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么这个对象的类型通过反射显示没有接口,尽管实现了至

发布时间:2020-12-15 06:25:55 所属栏目:百科 来源:网络整理
导读:首先是一个可以预期的工作的例子:(所有代码都在VS2008立即窗口中执行) 25 is IComparable true25.GetType().GetInterfaces() {System.Type[5]} [0]: {Name = "IComparable" FullName = ... [1]: {Name = "IFormattable" FullName = ... ... 到现在为止还挺
首先是一个可以预期的工作的例子:(所有代码都在VS2008立即窗口中执行)
25 is IComparable
>> true

25.GetType().GetInterfaces()
>> {System.Type[5]}
>>   [0]: {Name = "IComparable" FullName = ...
>>   [1]: {Name = "IFormattable" FullName = ...
>>   ...

到现在为止还挺好.现在让我们尝试一个通过基本类型继承接口的对象:

class TestBase : IComparable
{
    public int CompareTo(object obj) { throw new NotImplementedException(); }
}

class TheTest : TestBase { }

在即时窗口中:

(new TheTest()) is IComparable
>> true

(new TheTest()).GetType().GetInterfaces()
>> {System.Type[1]}
>>   [0]: {Name = "IComparable" FullName = "System.IComparable"}

这里也没有惊喜.那么下面的代码怎么没有显示任何接口呢?

wcfChannel = ChannelFactory<IMyServiceApi>.CreateChannel(binding,endpointAddress);

wcfChannel is IMyServiceApi && wcfChannel is ICommunicationObject
>> true

typeof(IMyServiceApi).IsInterface && typeof(ICommunicationObject).IsInterface
>> true

wcfChannel.GetType().GetInterfaces()
>> {System.Type[0]}

以上所有这些都可以同时实现?

(编辑:添加wcfChannel是上面的ICommunicationObject,这是在这个时候无法解释的解释如何wcfChannel是IMyServiceApi是真的.)

解决方法

这是因为wcfChannel的类型是接口本身:
>> channel.GetType().FullName
"MyService.IMyServiceApi"

>> channel.GetType().IsInterface
true

>> channel.GetType() == typeof(IMyServiceApi)
true

.GetInterfaces()只返回继承或实现的接口,而不是接口本身.

诚然,对象实例实际上是一个接口类型是不寻常的,但正如您在该问题的评论中提到的,该对象实际上是一个透明的代理.该代理对于实际的接口实现是不可知的,只关心接口是有意义的.事实上,.GetType()返回的接口使代理尽可能透明.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读