当存在逻辑时,属性是否应转换为具有支持字段的属性?

时间:2016-12-20 15:49:46

标签: c# .net visual-studio visual-studio-2013

如果我有一个具有内置逻辑的属性的类,例如:

class myModelClass
{
    public List<SummaryModel> Coupons {get;set;}

    public decimal AlaCarteTotal
    {
        get
        {
            if (Coupons != null)
            {
                if (!Coupons.Any(x => x.GromotionApplied))
                {
                    return Coupons.Sum(x => x.DefaultPrice);
                }

                return Coupons.Sum(x => x.GromotionApplied ? x.GromoPrice : x.DefaultPrice);
            }

            return default(decimal);
        }
    }
}

...最好将优惠券转换为支持字段,例如:

class myModelClass
{
    public List<SummaryModel> Coupons 
    { 
        get 
        { 
            return _Coupons; 
        } 
        set 
        { 
            _Coupons = value; 
        } 
    }

    public decimal AlaCarteTotal
    {
        get
        {
            if (_Coupons != null)
            {
                if (!_Coupons.Any(x => x.GromotionApplied))
                {
                    return _Coupons.Sum(x => x.DefaultPrice);
                }

                return _Coupons.Sum(x => x.GromotionApplied ? x.GromoPrice : x.DefaultPrice);
            }

            return default(decimal);
        }
    }
}

更一般地说,当模型类包含某种getter逻辑时,是否应该将属性转换为具有支持字段的属性?

1 个答案:

答案 0 :(得分:2)

没有一般性建议。

有时您会在代码中使用一些局部变量,并且随着时间的推移,您会发​​现需要更复杂的工作流来设置和获取该值。

如果您已将您的字段作为属性(甚至是通用的)setter和getter,那么您可以更轻松地完成生活,因为您只需编辑获取和设置而无需触及其余代码。

简而言之:保持它没有支持字段,直到你有目的。 .NET无论如何都会在后台创建它,但如果你的逻辑不需要它们,你的代码会更短,更简短。

这个可以解释得更多:Properties backing field - What is it good for?