C#接口inheritance
鉴于:
public interface IA { void TestMethod(); } public interface IB : IA { }
为什么:
typeof(IB).GetMethods().Count() == 0;
?
要明确一点:
public class A { public void TestMethod() { } } public class B : A { } typeof(B).GetMethods().Count();
确实有效(它返回5);
作为奖励:
typeof(IB).BaseType == null
以下是获取IA和IB计数的代码:
var ibCount = typeof(IB).GetMethods().Count(); // returns 0 var iaCount = typeof (IB).GetInterfaces()[0].GetMethods().Count(); // return 1
请注意,在生产代码中我不会使用GetInterfaces()[0]
作为我将使用它的代码中的典型代码我不能假设我将始终至少有一个接口。
我也尝试了如下的绑定标志:
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; var ibCount = typeof(IB).GetMethods(bindingFlags).Count();
但是,由于接口IB
仍未实现方法TestMethod()
,因此仍将返回0。 接口IA
。 如果IA
和IB
都是类,则使用绑定标志会起作用。 但是,在这种情况下,返回值为5.不要忘记IA隐式派生自Object
类!
这似乎是GetMethods函数的设计。 它不支持接口中的inheritance成员。 如果要发现所有方法,则需要直接查询每种接口类型。
查看此MSDN文章的社区内容部分。
考虑IA是IB的接口,而不是它的基础。
你必须在GetMethods()中定义一些Bindingflags。
尝试
上述就是C#学习教程:C#接口inheritance分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
typeof(IB).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Count();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1010793.html