开发者

Is it possible to hide properties from a derived class?

Class A derive from class B. In class A I want开发者_运维知识库 to hide some properties inherited from class B. So when an instance is created of class A, I don't want to expose some properties from class B.

Is this possible?


No, that would defeat the purpose of inheritance. Your class A is a B , thus it has the properties of B


Is it possible to use private access specifier to your property which you want to hide?

if not, then please go through this link - might help you - c# hide from dervied classes some properties of base class


You can shadow the members by declaring new ones with the same name (and the new modifier). But that doesn't really hide anything, and doesn't prevent anyone from casting back to B and accessing the members that way.

Are you sure you really want to use inheritance in this case? You may want to read up on http://en.wikipedia.org/wiki/Liskov_substitution_principle


When you derive A from B, you're saying that A is practically the same as B, but it has additional characteristics; it is a specialization of B.

To make an example: a Dog is an Animal. In you're case, you're trying to say that an Animal has fins, but a Dog hasn't; this is definitely not the purpose of inheritance.


For achieving that, rather than working on making the property private, avoid inheritance and apply composition (i.e. use interfaces).


Do you mean like:

class A {
    public virtual int X {
        get { return 1; }
    }
}

class B : A {
    public sealed override int X {
        get { return 2; }
    }
}

class C : B {
    public override int X {
        get { return -1; }
    }
}

If so, yes. (The above provides a compile-time error in C). The meaning here is that A had a property, B implemented it, and wanted to stop anyone sub-classes from doing so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜