C#接口继承 [英] C# interface inheritance

查看:198
本文介绍了C#接口继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

 公共接口IA 
{
无效TestMethod的();
}

公共接口IB:IA
{
}

为什么:

  typeof运算(IB).GetMethods()计数()== 0; ?





只是要清楚:

 大众A级
{
公共无效TestMethod的()
{
}
}

公共b类:A
{
}

typeof运算(b).GetMethods()计数();



不工作(返回5);



作为奖励:

  typeof运算(IB).BaseType == NULL 


解决方案

下面是获得的计数为IA和IB代码:

  VAR ibCount = typeof运算(IB).GetMethods()计数()。 //返回0 
VAR iaCount = typeof运算(IB).GetInterfaces()[0] .GetMethods()计数()。 //返回1

请注意,在生产代码,我不会用 GetInterfaces ()[0] 作为典型的代码,我会用这个我不能假设我会永远都至少有一个接口。



我也试过了的BindingFlags如下:

 常量的BindingFlags的BindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; 
VAR ibCount = typeof运算(IB).GetMethods(的BindingFlags).Count之间的();



不过,这仍然会返回0作为接口 IB 仍然没有实现方法 TestMethod的()。接口 IA 一样。如果两个 IA IB 是类中使用绑定标志会的工作。然而,在这种情况下,你得到5.返回值不要忘记,IA隐式地从类对象


派生

Given:

public interface IA
{
    void TestMethod();
}

public interface IB : IA
{
}

Why:

typeof(IB).GetMethods().Count() == 0;

?

Just to be clear:

public class A
{
    public void TestMethod()
    {
    }
}

public class B : A
{
}

typeof(B).GetMethods().Count();

does work (it returns 5);

As a bonus:

typeof(IB).BaseType == null

解决方案

Here is the code for getting the counts for both IA and IB:

var ibCount = typeof(IB).GetMethods().Count(); // returns 0
var iaCount = typeof (IB).GetInterfaces()[0].GetMethods().Count(); // return 1

Note that in production code I wouldn't use GetInterfaces()[0] as typically in the code where I would use this I can't assume that I will always have at least one interface.

I also tried out the bindingflags as follows:

const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
var ibCount = typeof(IB).GetMethods(bindingFlags).Count();

However, this will still return 0 as interface IB still doesn't implement method TestMethod(). Interface IA does. Using binding flags would work if both IA and IB were classes. In that case however, you get a return value of 5. Don't forget that IA implicitly derives from class Object!

这篇关于C#接口继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆