What is the best practice for using public fields?

后端 未结 11 1287
旧时难觅i
旧时难觅i 2020-12-03 03:07

When I write a class I always expose private fields through a public property like this:

private int _MyField;
public int MyField
{ get{return _MyField; }
         


        
11条回答
  •  离开以前
    2020-12-03 03:41

    The best practice is to use properties for several reasons. First, it decouples the API from the underlying data structure. Second, anything built into the framework that binds to objects does to to properties, not fields.

    I'm sure there are more reasons, but those two always seem to be enough for me.

提交回复
热议问题