ppi*_*icz 16 c# reflection inheritance interface
鉴于:
public interface IA
{
void TestMethod();
}
public interface IB : IA
{
}
Run Code Online (Sandbox Code Playgroud)
为什么:
typeof(IB).GetMethods().Count() == 0;
Run Code Online (Sandbox Code Playgroud)
?
只是要清楚:
public class A
{
public void TestMethod()
{
}
}
public class B : A
{
}
typeof(B).GetMethods().Count();
Run Code Online (Sandbox Code Playgroud)
确实有效(它返回5);
作为奖励:
typeof(IB).BaseType == null
Run Code Online (Sandbox Code Playgroud)
Man*_*red 11
以下是获取IA和IB计数的代码:
var ibCount = typeof(IB).GetMethods().Count(); // returns 0
var iaCount = typeof (IB).GetInterfaces()[0].GetMethods().Count(); // return 1
Run Code Online (Sandbox Code Playgroud)
请注意,在生产代码中我不会GetInterfaces()[0]像在我将使用它的代码中那样使用我不能假设我将始终至少有一个接口.
我也尝试了如下的绑定标志:
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
var ibCount = typeof(IB).GetMethods(bindingFlags).Count();
Run Code Online (Sandbox Code Playgroud)
但是,由于接口IB仍未实现方法,因此仍将返回0 TestMethod().接口呢IA.如果同时使用绑定标志将工作IA和IB为类.但是,在这种情况下,返回值为5.不要忘记IA隐式派生于类Object!
小智 -1
您必须在 GetMethods() 中定义一些 Bindingflags。
尝试
typeof(IB).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Count();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3552 次 |
| 最近记录: |