简体   繁体   中英

Inheritance and interfaces .NET

Quirky question:

Imagine that I have a base class called BaseFoo. I have an interface with some methods called IFoo. And I have tons of classes beneath BaseFoo.

If i implement the interface in BaseFoo, i dont need to implement in the inherited classes, correct?

Ok, but imagine that i have a generic function that will treat IFoo's. Do i need to explicitely declare that they implement IFoo?

Like this (pseudo-illustrational-code)

public class BaseFoo:IFoo;

public interface IFoo;

Should i do this?

public class AmbarFoo:BaseFoo,IFoo

or?

public class AmbarFoo:BaseFoo

What is the most correct way? Are the effects the same? If i test if AmbarFoo is a IFoo what will I get?

Thanks

It will behave the same way regardless. You'd only need to restate the interface name if you wanted to reimplement the interface with explicit interface implementation. An instance of AmbarFoo will indeed "say" that it implements IFoo .

If i implement the interface in BaseFoo, i dont need to implement in the inherited classes, correct?

No, because BaseFoo will be forced to implement, and the child classes will inherit the implementation. They will all still be IFoos though.

In your case it won't change anything.

However, look at the following one:

public interface IFoo
{
    void Bar();
}

public class FooBase
    : IFoo
{
    public void Bar()
    {
        Console.WriteLine("FooBase");
    }
}

public sealed class SubFoo
    : FooBase//, IFoo
{
    public new void Bar()
    {
        Console.WriteLine("SubFoo");
    }
}

Now run the following and comment out the "//, IFoo".

SubFoo foo = new SubFoo();

foo.Bar();
((IFoo) foo).Bar();

However, this is more theoretically.

Leave it away.

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