C#:inheritance for a child class that does have a property from parent
I am thinking whether it is possible to have something like开发者_如何学运维 this:
public class A
{
public void methodA(){}
}
public class B:A
{
}
In such the way that: B does not see the methodA from A, so it is not possible to call:
B.methodA()
?
No. Doing what you are suggesting would violate the Liskov Substitution Principle, which is one of the main concepts that is core to inheritance.
If "B" does not behave exactly like "A", and an "A" is not replaceable at runtime with a "B", then you should not make B
subclass A
.
What you ask is not possible.
I don't know what you are trying to do. But, if you need to achieve similar behaviour, one way to do this is as follows:
public class C
{
// Other methods from class A than MethodA()
}
public class A
{
public void MethodA()
{
// Some code
}
}
public class B : C
{
// Some code
}
Yes, mark MethodA
as private. If you want it to be public then there's no good reason (or way to) allow outside callers to call the method but only block B
.
If you wanted B
to be able to 'delete' a method defined by A
, then you don't want inheritance in the first place.
You could override methodA
in B
and throw a NotImplementedException
when it is thrown. But if you're thinking about doing this, you should ask yourself if B
should really be inheriting from A
.
Nope! Never do this. You are breaking "is a" paradigm. Use "has a" to implement such behavior. Don't use inheritance. Make B has property of type A.
public class A
{
public void methodA(){}
}
public class B
{
private A _a
}
If you use inheritance B:A. You clearly mention in this way that "B is A" but with some specification. If you see that B don't implement full A interface then there should be no inheritance relation between this types.
Bottom line: You can't. That is not what inheritance is about.
If you're in this situation you should rethink why you're deriving the class in the first place. If the subclass doesn't contain all the methods of the super class, they shouldn't be related in such a way.
Defining B as a subclass of A is akin to saying B will provide all the functionality that A does, plus (whatever else you decide to define). You should re-structure your class hierarchy in this situation.
If you want something like this:
public class A
{
public void sharedFuncA(){}
public void sharedFuncB(){}
public void sharedFuncC(){}
public void methodA(){}
}
public class B:A
{
public void sharedFuncA(){}
public void sharedFuncB(){}
public void sharedFuncC(){}
public void BOnlyFunction(){}
}
You should structure the classes like this instead:
public class A : C
{
public void methodA(){}
}
public class B:C
{
public void BOnlyFunction();
}
public class C
{
public void sharedFuncA(){}
public void sharedFuncB(){}
public void sharedFuncC(){}
}
精彩评论