简体   繁体   English

C#属性,这是一个不好的做法吗?

[英]C# Properties, is this a bad practice?

I'm new to C# and OOP in general. 我是C#和OOP的新手。 I've just learned about Properties in c# -which have a get and set method. 我刚刚了解了c#中的Properties-具有get和set方法。

Is it bad practice to update one property from within the Set of another property like in the code example below? 从另一个属性的Set中更新一个属性是一种不好的做法,如下面的代码示例所示?

    private int _prop1;

    public int Prop1
    {
        get { return _prop1; }
        set { _prop1 = value; OnPropertyChanged("Prop1"); Prop2 = value; }
    }

    private int _prop2;

    public int Prop2
    {
        get { return _prop2; }
        set { _prop2 = value; }
    }

I would say it is bad practice if both properties are read-write, because of the confusion it could create. 我会说如果两个属性都是可读写的,则是不好的做法,因为这可能会造成混乱。 It is OK though if the affected property is readonly. 如果受影响的属性为只读也可以。 Here is an OK example: 这是一个好的示例:

public int LivesRemaining {get; set;}

public bool IsDead {get => LivesRemaining == 0}

Setting LivesRemaining = 0 will cause the IsDead property to become true . 设置LivesRemaining = 0将导致IsDead属性变为true But this is hardly surprising or confusing. 但这不足为奇或令人困惑。

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

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