Purpose of automatic properties in .NET
Why is this:
public string Foo {get;set;}
considered better than thi开发者_如何学运维s:
public string Foo;
I can't for the life of me work it out. Can anyone shed some light?
Thanks
Because you can transparently (from client code's perspective) change the implementation of the setter/getter wheras you cannot do the same, if you expose the underlying property directly (as it would not be binary compatible.)
There is a certain code smell associated with automatic properties, though, in that they make it far to easy to expose some part of your class' state without a second thought. This has befallen Java as well, where in many projects you find get/setXxx
pairs all over the place exposing internal state (often without any need for it, "just in case"), which renders the properties essentially public.
While the purpose of a field is object state storage, the purpose of a property is merely access. The difference may be more conceptual than practical, but automatic properties provides a handy syntax for declaring both.
精彩评论