简体   繁体   中英

How to cast derived class to base with new properties?

I have a base class and derived class. Derived class has same property as base class but it needs always return same value/readonly

public class BaseClass 
{
    public int Id {get; set;}
    public TransactionTypeEnum TransactionType {get; set;}
}

public class DerivedClass: BaseClass 
{
    public new TransactionTypeEnum TransactionType {get;} = TransactionTypeEnum.Credit;
}

The problem with this is when I cast derived class to base I of course end up with 2 properties: one from base and one from derived. I could also declare TransactionType property as virtual and then override it in derived class but then I'm forced to add setter method. What's the best course of action in this case? Create a mapper between these 2 classes ?

From my perspective, your desire violates the Liskov substitution principle ( see here ): your base class defines a settable TransactionType . Since every derived class inherits that behavior, you either shouldn't break it or remove the behavior - ie remove the setter. Maybe the derived class isn't a real inheritor?

Another approach could look like this (protected setter):

public class BaseClass 
{
    public int Id {get; set;}
    public TransactionTypeEnum TransactionType { get; protected set; }
}

public class DerivedClass: BaseClass 
{
    public DerivedClass()
    {
        TransactionType = TransactionTypeEnum.Credit;
    }
}

you can make the property in the BaseClass virtual and then override it in the DerivedClass using a lambda expression to avoid the setter.

public class BaseClass 
{
    public int Id {get; set;}
    public virtual TransactionTypeEnum TransactionType {get; set;}
}

public class DerivedClass: BaseClass 
{
    public override TransactionTypeEnum TransactionType => TransactionTypeEnum.Credit;
}

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