Why do I need a private field that is exposed via public property?

前端 未结 11 740
天涯浪人
天涯浪人 2020-12-11 11:41

I\'m comming from Java world mainly. So, C# properties do look nice.

I know that with C# 3.0 or above I can use Automatic Properties. I like it even more :).

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 12:04

    Maybe you want to change the behaviour of the setter or getter at a later point. e.g. log that the value was changed from outside. this would not be possible with a public field without properties

       private int age;
    
       public int Age {
    
         get { return age; }
         set { 
           age = value; 
           Log("value of age changed");
         }     
       }
    

    With a public field age, you had to log this everywhere in the code where you change the value of age.

提交回复
热议问题