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 开发者_JAVA百科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.
精彩评论