C# 为什么这个对象';s类型通过反射不显示接口,尽管至少实现了两个?

C# 为什么这个对象';s类型通过反射不显示接口,尽管至少实现了两个?,c#,.net,reflection,interface,C#,.net,Reflection,Interface,首先,一个按预期工作的示例:(所有代码都在VS2008即时窗口中执行) 到目前为止还不错。现在,让我们在通过基类型继承接口的对象上进行尝试: class TestBase : IComparable { public int CompareTo(object obj) { throw new NotImplementedException(); } } class TheTest : TestBase { } 在即时窗口中: (new TheTest()) is IComparabl

首先,一个按预期工作的示例:(所有代码都在VS2008即时窗口中执行)

到目前为止还不错。现在,让我们在通过基类型继承接口的对象上进行尝试:

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=ChannelFactory.CreateChannel(绑定,端点地址);
wcfChannel是IMyServiceApi&wcfChannel是ICommunicationObject
>>真的
typeof(IMyServiceApi).IsInterface&&typeof(ICommunicationObject).IsInterface
>>真的
wcfChannel.GetType().GetInterfaces()
>>{System.Type[0]}
如何能同时实现上述所有要求


edit:添加了上面的
wcfChannel是ICommunicationObject
,解释
wcfChannel如何是IMyServiceApi
的答案目前无法解释这一点。)

这是因为
wcfChannel
的类型是接口本身:

>> channel.GetType().FullName
"MyService.IMyServiceApi"

>> channel.GetType().IsInterface
true

>> channel.GetType() == typeof(IMyServiceApi)
true
.GetInterfaces()
只返回继承或实现的接口,而不返回接口本身


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

这可能是在运行时生成此类型的一个副作用;出于好奇,它是ContextBoundObject吗?进一步信息:Visual Studio将其显示为
系统.Runtime.Remoting.Proxies.\uu TransparentProxy
。在任何地方都看不到ContextBoundObject。第二个问题:为什么
频道是ICommunicationObject
也是
true
?:)我现在意识到这都是由于“通道”是一个.NET远程对象,但是反射是否暴露了
channel
以任何方式实现
ICommunicationObject
的事实?
>> channel.GetType().FullName
"MyService.IMyServiceApi"

>> channel.GetType().IsInterface
true

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