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()返回接口的事实使代理尽可能透明.
| 归档时间: |
|
| 查看次数: |
444 次 |
| 最近记录: |