Inheritance and .NET Interfaces

Bizarre question:

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

If I implement an interface in BaseFoo, I should not implement in inherited classes, right?

Ok, but imagine that I have a generic function that will handle IFoo. Do I need to explicitly declare that they implement IFoo?

Like this (pseudo-illustrative 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 IFoo, what will I get?

thank

+3
source share
3 answers

. , . AmbarFoo "", IFoo.

+7

BaseFoo, , ?

, BaseFoo , . IFOos.

0

In your case, this will not change anything.

However, look at the following:

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 "//, ifoo".

SubFoo foo = new SubFoo();

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

However, this is more theoretical.

Leave it.

0
source

Source: https://habr.com/ru/post/1728645/


All Articles