C# getter and setter shorthand

前端 未结 5 1883
遥遥无期
遥遥无期 2021-02-13 06:24

If my understanding of the internal workings of this line is correct:

public int MyInt { get; set; }

Then it behind the scenes does this:

5条回答
  •  -上瘾入骨i
    2021-02-13 06:38

    You'll need to handle this yourself:

    private bool IsDirty { get; set; }
    
    private int _myInt; // Doesn't need to be a property
    Public int MyInt {
        get{return _myInt;}
        set{_myInt = value; IsDirty = true;}
    }
    

    There is no syntax available which adds custom logic to a setter while still using the automatic property mechanism. You'll need to write this with your own backing field.

    This is a common issue - for example, when implementing INotifyPropertyChanged.

提交回复
热议问题