简体   繁体   English

C#多接口继承

[英]C# Multiple Interface Inheritance

Given the following code: 给出以下代码:

interface IParent
{
    void ParentPrintMethod();
}

interface IChild : IParent
{ 
    void ChildPrintMethod();
}

class Baby : IChild
{
    public void ParentPrintMethod()
    {
       Console.WriteLine("Parent Print Method");
    }

    public void ChildPrintMethod()
    {
       Console.WriteLine("Child Print Method");
    }

}

All is well at this point. 此时一切都很好。 If you were to create a new instance of the Baby class as follows, 如果您要按如下方式创建Baby类的新实例,

Baby x = new Baby();

everything is ok, and you would have access to the ParentPrintMethod() and the ChildPrintMethod(); 一切正常,您将可以访问ParentPrintMethod()和ChildPrintMethod();。

However, can somebody please explain to me what would happen if you were to do the following? 但是,有人可以向我解释一下,如果您执行以下操作会怎样?

IParent x = new Baby();

Would you have access to the ChildPrintMethod() in this case? 在这种情况下,您可以访问ChildPrintMethod()吗? What exactly is happening when you do this? 当您这样做时到底发生了什么?

然后,您指定您仅对Parent声明的Interface感兴趣,因此即使对象本身的实例具有更多可用性,您也只能访问Parent声明的那些方法。

No, you would not. 不,你不会。 The variable x , as type Parent (by the by, interfaces are idiomatically named with an I at the beginning) would only see the methods defined in the Parent interface. 变量x (作为Parent类型)(按by,接口在开头以惯用语I命名)只能看到在Parent接口中定义的方法。 Period. 期。

您对该对象的引用的行为将类似于Parent接口的实例,并且将无法访问Child方法。

This sounds really abnormal but: All Child ren are Parent s, but not all Parent s are Child ren. 这听起来确实很不正常,但是:所有Child都是Parent ,但并非所有Parent都是Child

It doesn't make sense for a Parent to access a Child s methods because it would be an error in the case that the parent isn't a child. Parent访问Child的方法没有意义,因为在父级不是孩子的情况下这将是一个错误。

It is still possible to access the child methods in your example given, but you must cast x to a Child first, ((Child)x).ChildPrintMethod() . 它仍然可以访问你的榜样孩子的方法给出的,但是你必须投xChild第一, ((Child)x).ChildPrintMethod() This is sound because in the event that x is not a valid Child, an exception is thrown when the cast happens, rather than attempting to run the method. 这是合理的,因为如果x不是有效的Child,则在进行强制类型转换时会抛出异常,而不是尝试运行该方法。

You can test ahead whether this should work, rather than having to catch exceptions by using if (x is Child) 您可以预先测试这是否应该工作,而不必使用if (x is Child)捕获异常

Edit: 编辑:

To reuse the variable as if it were a child, you can create a local reference to it like this: 要像子变量一样重用该变量,可以像这样创建一个本地引用:

if (x is Child) {
    Child y = (Child)x;
    ...
}

There is no such thing as "inheritance skipped". 没有“继承遗漏”之类的东西。 Your object is just viewed 'through' one of its interfaces, effectively hiding anything else not declared in that interface. 您的对象只是通过其接口之一“查看”,有效地隐藏了该接口中未声明的任何其他内容。 There's no magic in it. 里面没有魔术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM