简体   繁体   中英

How to inherit few properties from base class

I have come across a scenario where I have to inherit only few properties from base class and leave other properties as it is.

So for example

class A
{
    public string A1
    public string A2
}

class B : A
{
    public string A3;
    public string B1;
}

Now I should be able to use properties like B.A1,B.B1 and B.A3, But I don't want A2 to be available in class B***. Remember I don't want to use private*** , I have to keep it public because its a mongo entity document and need to be stored in mongo DB

Basically I am trying to share few common properties between two entities using inheritance.

Refactor.

class AA
{
    public string A1 { get; set; }
}

class A : AA
{
    public string A2 { get; set; }
}

class B : AA
{
    public string A3  { get; set; }
    public string B1  { get; set; }
}

Well, if we don't want property A2 to be accessible from derived class B we (most likely) shouldn't use inheritance in the first place. We could use aggregation instead:

class A
{
    public string A1 { get; set; }
    public string A2 { get; set; }
}

class B
{
    public string A1 { get; set; }
    public string A3 { get; set; }
    public string B1 { get; set; }

    public B(A instance)
    {
       this.A1 = instance.A1;
    }
}

You can hide public variables by shadowing them with private ones.

class Base {
    public string P1 { get; set; }
    public string P2 { get; set; }
}

class Limited: Base {
    new private string P1 { get; set; }
    // P2 will be inherited as public, P1 will be hidden to the user
}

Although I would take a step back and consider encapsulation instead of inheritance. This hide-and-seek with property attributes smells.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM