C# getter and setter shorthand

前端 未结 5 1916
遥遥无期
遥遥无期 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:48

    I have created a custom Property class to do common operations like that. I haven't used it thoroughly yet though, but it could be used in this scenario.

    Code can be found here: http://pastebin.com/RWTWNNCU

    You could use it as follows:

    readonly Property _myInt = new Property();
    public int MyInt
    {
        get { return _myInt.GetValue(); }
        set { _myInt.SetValue( value, SetterCallbackOption.OnNewValue, SetDirty ); }
    }
    
    private void SetDirty( int oldValue, int newValue )
    {
        IsDirty = true;
    }
    

    The Property class handles only calling the passed delegate when a new value is passed thanks to the SetterCallbackOption parameter. This is default so it can be dropped.

    UPDATE:

    This won't work apparently when you need to support multiple types (besides int), because the delegate won't match then. You could ofcourse always adjust the code to suit your needs.

提交回复
热议问题