How to Inheried Interface methods through to the subclasses in C#
I have:
I:
public interface I
{
void Something();
}
A:
public class A : I
{
public void Something()
{
}
}
B:
public class B : A
{
}
Why isn't B forced to implement (the decired) Something method, as expected?
开发者_如何学CDo I really have to inheried I on all my B's(subclasses to A)?
public class B : A, I
{
public void Something()
{
}
}
Because B
already has a Something
method which inherited from A
.
So B
is not forced to implement Something
method. B on the other hand, it's free to override A
's Something
method if it needs to, provided Something
method was marked as virtual
in class A
:
public class B : A
{
public override void Something()
{
// B's something
}
}
B isn't forced to implement I, because it's already implemented in A.
If you want to force B to implement it, you have to make it abstract in A, or not implement the interface on A, only implement I in B.
On a different note, if you want to allow B to override the method defined in A, you should make the method virtual in A, and then use the override keyword to override the method in B. Right now your Something method is not virtual in A, so if you try to override it in B, the compiler will either give you and error or a warning stating that you are "hiding" the method Something in a base class.
Why would you expect it to? Since B is already deriving from A, it has the method implemented in A. Therefore it need not implement the method again in B
Think of B as an union of A and B classes. So B essentially has all the methods implemented in A. Also A cannot reduce the scope of method from public
to private
, so there is no way B cannot have access to something
function.
精彩评论