What is the best practice for using public fields?

后端 未结 11 1325
旧时难觅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:44

    I recommend using something similar to this:

    public class Result{  
        public bool Result {  get; protected set; }
        public string Message {  get; protected set; }
    
        public Result(bool result, string message) {
            Result = result;
            Message = message;
        }
    }
    

    This way, you don't need to declare member variables, let the compiler do the work for you! The code is very clean and short, and refactoring is a breeze.

提交回复
热议问题