Property vs Function (specifically .NET)

后端 未结 6 2121
花落未央
花落未央 2021-01-12 11:20

I\'ve read some discussions about this subject, and there\'s something I just don\'t understand.

The most common answer seems to be this: use a ReadOnly Property to

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 12:08

    There is more to properties than auto properties. If you do:

    public int MyProp { public get; public set; }
    

    Then it's really no different from

    public int MyProp;
    

    But the big advantage of the former is that you can later change it to:

    public int MyProp {
        get {
            // Do some processing
            return someValue;
        }
    
        set {
            // Do some processing
            DoMyProcess(value);
        }
    }
    

    And other code that uses your object would work without recompiling. If, instead, you had used a public field, client code would need to be recompiled if you ever want to change it from a field to a property.

提交回复
热议问题