Getter without body, Setter with

半城伤御伤魂 提交于 2019-12-03 23:35:45

问题


I have a property which is currently automatic.

public string MyProperty { get; set; }

However, I now need it to perform some action every time it changes, so I want to add logic to the setter. So I want to do something like:

public string MyProperty {
    get;
    set { PerformSomeAction(); }
}

However, this doesn't build... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial

I can't just have the getter return MyProperty as it will cause an infinite loop.

Is there a way of doing this, or do I have to declare a private variable to refer to? I'd rather not as MyProperty is used through out the code both in this class and outside it


回答1:


You need to use a property with backing field:

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



回答2:


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?




回答3:


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();
    }
}



回答4:


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()




回答5:


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.



来源:https://stackoverflow.com/questions/37392253/getter-without-body-setter-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!