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

前端 未结 11 739
天涯浪人
天涯浪人 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 11:52

    Older versions of C# didn't have automatic properties, so you had to declare your variables that the properties acted upon like in your example. These days, the same code could be expressed as:

    public int Age { get; set; }
    

    I think that answers your question. However, if you are asking "why not just have public int Age; and let programmers set the value on the field directly?", then:

    First thing to keep in mind is that property accessors are compiled into methods. This means that it has a different ABI from just reading/writing to a class member variable, even though it may syntactically look the same as if you had:

    class Fu {
      public int Age;
    }
    

    So, what this means is that if, at some point down the road, you need to add some notification that the Age field has changed - if you are using properties, you can easily add this notification logic to the property setter without breaking ABI.

    public int Age {
      get { return age; }
      set { age = value; NotifySomeOtherCode (); }
    }
    

    If you start off with a public field, then later changing it to a property will change the ABI which is bad for any program(s) that may depend on your assembly. So it's better to start off with properties.

    Hopefully I'm making sense...

提交回复
热议问题