Getter without body, Setter with

后端 未结 5 641
死守一世寂寞
死守一世寂寞 2021-01-01 11:21

I have a property which is currently automatic.

public string MyProperty { get; set; }

However, I now need it to perform some action every

相关标签:
5条回答
  • 2021-01-01 12:02

    You need to use a property with backing field:

    private string mMyProperty;
    public string MyProperty
    {
        get { return mMyProperty; }
        set
        {
            mMyProperty = value;
            PerformSomeAction();
        }
    }
    
    0 讨论(0)
  • 2021-01-01 12:02

    This is similar to the question C# getter and setter shorthand.

    When you manually specify a setter, it won't use the automatic property mechanism for the getter, which is why the error message acts like it's missing. You'll need to write your own getter when you specify the setter.

    0 讨论(0)
  • 2021-01-01 12:07

    You need to either provide a body for both the getter and setter, or neither.

    So if you define either one, it's no longer an auto property.

    So you have to do:

    Either

    public string MyProperty {
        get;
        set;
    }// Automatic property, no implementation
    

    OR

    public string MyProperty
    {
        get { return mMyProperty; }
        set
        {
            mMyProperty = value;
            PerformSomeAction();
        }
    }
    
    0 讨论(0)
  • 2021-01-01 12:13

    If you are doing something in the setter then you will have to explicitly declare the variable. E.g.

    private string _myProperty;
    public string MyProperty {
        get { return _myProperty; };
        set 
        {
            _myProperty = value; 
            PerformSomeAction(); 
        }
    }
    

    or - in the setter you can pass value to the function and do what you want to it there... assuming you want to change/check the value in the function PerformSomeAction()

    0 讨论(0)
  • 2021-01-01 12:24

    You can´t implement one without the other, as when using the one it refers to a (hidden) backing-field which is auto-generated in the case of an autogenerated property. However when you implement one you have to set this backing-field in both ways.

    The auto-way is just a shortcut for this:

    private string _property;
    public string MyProperty
    {
        get { return _property; }
        set { _property = value; }
    }
    

    So if you´d omit the hidden field in one of the methods (this is what getters and setters are actually) how should this method know how to store/get the value?

    0 讨论(0)
提交回复
热议问题