简体   繁体   English

如何使用新属性将派生类转换为基类?

[英]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.问题是当我将派生类转换为基类时,我当然会得到 2 个属性:一个来自基类,一个来自派生类。 I could also declare TransactionType property as virtual and then override it in derived class but then I'm forced to add setter method.我也可以将 TransactionType 属性声明为虚拟,然后在派生类中覆盖它,但随后我不得不添加 setter 方法。 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 .从我的角度来看,您的愿望违反了Liskov 替换原则请参阅此处):您的基类定义了一个可设置的TransactionType Since every derived class inherits that behavior, you either shouldn't break it or remove the behavior - ie remove the setter.由于每个派生类都继承了该行为,因此您不应该破坏它或删除该行为 - 即删除 setter。 Maybe the derived class isn't a real inheritor?也许派生类不是真正的继承者?

Another approach could look like this (protected setter):另一种方法可能如下所示(受保护的 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.您可以将BaseClass的属性设为虚拟,然后使用 lambda 表达式在 DerivedClass 中覆盖它以避免使用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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