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

前端 未结 8 925
清歌不尽
清歌不尽 2021-01-11 17:38

Do I need to declare a class-level variable to hold a property, or can I just refer to self.{propertyname} in the getter/setter?

In other words, can I d

相关标签:
8条回答
  • 2021-01-11 18:38

    You should have a backing variable. Take a closer look:

    get { return this.mongoFormId; }
    

    Is going to call the getter on mongoFormId, which will call that code again, and again, and again! Defining a backing variable will avoid the infinite recursive call.

    0 讨论(0)
  • 2021-01-11 18:40

    You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way).

    private string _mongoFormId;
    
    public string mongoFormId 
    {
        get { return this._mongoFormId; }
        set 
        {
            this._mongoFormId = value;
            revalidateTransformation();
        }
    }
    

    UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field.

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