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

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

    Properties (specially automatic properties in .net 3.5) are more concise than setters/getters, and less lines of code == less code to maintain == less bugs.

    I would say readability first, but you already said that won't count to you.. :)

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

    I know in some instances, you can use a property as a "Column" name like in a data set. I think .NET does this through introspection. I don't beleive this is possible with get/set functions.

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

    As usr states:

    "A property has a connotation of get being without side effects and both get and set being a fast operation."

    Exactly. It is implied that a getter/setter will be quick. By exposing something as property you're implying that you're quickly fetching/putting an attribute on an object. Methods are for doing some form of work assumed to involved more cycles than simply getting/setting an attribute. We usually will put a lengthy operation 'properties' into a GetFoo(...)/SetFoo(...) methods to indicate that the computation operation is heavier than a property.

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