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

前端 未结 11 714
天涯浪人
天涯浪人 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条回答
  •  醉梦人生
    2020-12-11 12:06

    Properties are just a nice way to write a pair of a get and a set method. In Java you would do this:

    private int age;
    
    public int getAge() { return age; }
    public void setAge(int value) { age = value; }
    

    You need the private field to store the age somewhere -- getAge and setAge are just methods.

    The same applies to C# to versions before 3.0:

    private int age;
    
    public int Age
    {
       get { return age; }
       set { age = value; } 
    }
    

    This is a get and a set method, just nicely paired up so you can write x.Age = 21 instead of x.setAge(21).

    With automatic properties, the C# compiler generates the private field for you (but it's still there!):

    public int Age
    {
       get;
       set;
    }
    

    The benefit of automatic properties is that you don't have to create the backing field manually yourself anymore.

    The benefit of the manual version is, that you can add additional logic to the get and set methods, for instance, parameter validation:

    private int age;
    
    public int Age
    {
       get { return age; }
       set { if (value < 0) throw new ArgumentException(); age = value; } 
    }
    

提交回复
热议问题