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

Rom*_*kov 10 .net c# reflection interface

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

25 is IComparable
>> true

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

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

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

class TheTest : TestBase { }
Run Code Online (Sandbox Code Playgroud)

在即时窗口中:

(new TheTest()) is IComparable
>> true

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

这里也没有惊喜.为什么以下代码不显示任何接口:

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]}
Run Code Online (Sandbox Code Playgroud)

如何才能同时实现以上所有目标?

(编辑:wcfChannel is ICommunicationObject上面补充说,这个时候解释得不正确的答案是无法解释的wcfChannel is IMyServiceApi.)

Tim*_*mwi 10

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

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

>> channel.GetType().IsInterface
true

>> channel.GetType() == typeof(IMyServiceApi)
true
Run Code Online (Sandbox Code Playgroud)

.GetInterfaces()仅返回继承或实现的接口,但不返回接口本身.

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

  • 挑战二:“channel is ICommunicationObject”怎么可能也是“true”?:) 我现在意识到这完全是“通道”是 .NET Remoting 对象的结果,但是反射是否暴露了`channel` 以任何方式实现了`ICommunicationObject` 的事实? (2认同)