Why do we use .NET properties instead of plain old get/set functions?

前端 未结 15 1748
自闭症患者
自闭症患者 2020-12-25 15:06

I understand the many benefits of providing an interface to access the members of a class indirectly. My question is: isn\'t that already something you can accomplish in jus

15条回答
  •  长发绾君心
    2020-12-25 15:10

    Jon Skeet has an excellent overview on his C# article blog about why properties matter. In it he explains why properties should be used over exposing public fields.

    As for why to use properties instead of getter/setter methods, I would suggest the following thoughts:

    • Properties provide a cleaner, more concise syntax that is easy to understand and read.
    • Properties enable assignment expression chaining: A.x = B.y = C.z
    • Properties convey the semantics of data access clearly and consistently - consumers expect that there are no side effects.
    • Properties are recognized by many libraries in .NET for tasks such as XML serialization, WPF bindings, ASP.NET 2-way binding, and more.
    • Properties are recognized by the IDE and many visual designers and can be displayed in a property editor.
    • Properties enable support for the increment (++) and decrement (--) operators.
    • Properties can be easily differentiated from methods using reflection and allow dynamic consumers to extract knowledge about the data exposed by an object.
    • C# 3 supports automatic properties which helps eliminate boilerplate code.

提交回复
热议问题