在接到电话之前修改价值

时间:2017-03-30 18:20:37

标签: c#

我有一个依赖于其他一些属性的属性,代码如下所示:

        get 
        {
            if (this.FuelType == "Benzin")
            {
                if (this.KmPrL >= 18)
                {
                    return 'A';
                }
                else if (this.KmPrL < 18 && this.KmPrL >= 14)
                {
                    return 'B';
                }
                else if (this.KmPrL < 14 && this.KmPrL >= 10)
                {
                    return 'C';
                }
                else
                {
                    return 'D';
                }
            }
        }

现在我有另一个类覆盖了这个get,我希望它使用这个get调用,但是KmPrL值乘以0.7,但是没有实际修改属性KmPrL。 我该怎么做呢?

2 个答案:

答案 0 :(得分:0)

我会做一些重构来实现这一点,将你对this.KmPrL的使用重构为这样的虚拟方法:

protected virtual GetKmPrL() //Or a more descriptive name
{
   return KmPrL
}

...
if (this.FuelType == "Benzin")
        {
            if (GetKmPrL() >= 18)
            {

然后你的派生类可以覆盖它:

protected override GetKmPrL()
{
   return KmPrL * .7
}

总的来说,你的getter属性看起来有点复杂,但是通过允许派生类覆盖你的依赖属性的计算,你将获得你正在寻找的行为。

答案 1 :(得分:0)

我会更改你的属性getter以在支票中使用你的因子。然后在覆盖中提供因子为0.7。

public virtual char FuelRating
{
    get
    {
        return CalculateRating(this.FuelType, this.KmPrL, 1.0);
    }
}

internal char CalculateRating(string fuelType, double kmprl, double factor)
{
    double x = kmprl * factor;
    if (this.FuelType == "Benzin")
    {
        if (x >= 18)
        {
            return 'A';
        }
        else if (x < 18 && x >= 14)
        {
            return 'B';
        }
        else if (x < 14 && x >= 10)
        {
            return 'C';
        }
        else
        {
            return 'D';
        }
    }
    else
        return char.MinValue;       // not clear what is expected for other fuel types.
}

然后在你的派生类中你会得到:

public override char FuelRating
{
    get
    {
        return CalculateRating(this.FuelType, this.KmPrL, 0.7);
    }
}

最后,另外,您应该小心在属性getter中执行复杂的逻辑。属性应该是轻量级的,如果其中有昂贵的操作,则可能会遇到性能问题。

相关问题