What is Property Accessor Recursion in C#?

扶醉桌前 提交于 2019-12-13 03:39:45

问题


What is Property Accessor Recursion in C#? I see articles of how to resolve it, but want a pure technical definition of what it is.

Resources on how to resolve it:

c# property setter body without declaring a class-level property variable


回答1:


It becomes clearer if you think of the getters and setters as methods (they really are methods in the background - C# just hides that from you).

  • Whenever you retrieve the value of a property, you are calling the get method
  • Whenever you set the value of a property, you are calling the set method

So if you have a property that looks like this:

public string MyProperty {
    get {
        return this.MyProperty;
    }
    set {
        this.MyProperty = value;
    }
}

That is really like having these two methods:

string get_MyProperty() {
    return get_MyProperty();
}

void set_MyProperty(string value) {
    set_MyProperty(value);
}

You will notice that both cases will result in infinite recursion that will end with a stack overflow.

So Don't Do That™



来源:https://stackoverflow.com/questions/57634401/what-is-property-accessor-recursion-in-c

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