简体   繁体   中英

Modifying value before get call

I have a property that is dependent on some other properties, code looks like this:

        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';
                }
            }
        }

Now I have another class that overrides this get, and I would like it to use this get call, but with the KmPrL value multiplied by 0.7, but without actually modifying the property KmPrL permanently. How would I go about doing that?

I would do some refactoring to accomplish this, refactor your usage of this.KmPrL to a virtual method like this:

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

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

Then your derived class can override it:

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

Overall your getter property looks a little complicated to start with but by allowing derived classes to override the calculation of your dependent property, you'll get the behavior you are looking for.

I would change your property getter to use your factor in the check. Then in the override provide the factor as 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.
}

Then in your derived class you would have:

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

Finally as an aside, you should be careful with doing complex logic in your property getter. Properties are supposed to be light weight, and if there costly operations within them, you may run into performance problems.

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