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

前端 未结 15 1684
自闭症患者
自闭症患者 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:09

    Maybe a minor point, but with getters /setters I find it annoying that when I'm cycling through them in an IDE with 'intellisense' there's a massive block of 'getters' next to each other and another block of 'setters'. I find it more difficult to find what I'm looking.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-25 15:12

    They allow the user of the type to have a simplified syntax, and allow you to create read-only and write-only fields. Thus me.SetAge(34); age = me.GetAge(); becomes me.age = 34; age = me.age;

    0 讨论(0)
  • 2020-12-25 15:13

    Aside from the semantic correctness of using properties for a value that describes a property of an object, you can't argue with this:

    obj.SetValue(obj.GetValue() + 1);
    

    vs

    obj.Value++;
    
    0 讨论(0)
  • 2020-12-25 15:14

    At least for DataBinding
    UI-related development becomes way more complex without it.

    0 讨论(0)
  • 2020-12-25 15:20

    I believe XML Serialization only reads/writes public properties, so your get and set methods would be ignored.

    Also, if you have a generic list of objects, you can assign that to a DataGridView.DataSource and you'll get a column for each of your properties. That may be what @LPalmer was referring to.

    0 讨论(0)
提交回复
热议问题