简体   繁体   中英

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 x = new Baby();

everything is ok, and you would have access to the ParentPrintMethod() and the 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? 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. Period.

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

This sounds really abnormal but: All Child ren are Parent s, but not all Parent s are Child ren.

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.

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() . 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.

You can test ahead whether this should work, rather than having to catch exceptions by using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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