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

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

    Properties at the essence are get/set method pairs.

    Properties are a runtime supported method of exposing a pair of get set methods that have metadata support which means they are discoverable using reflection without guessing what methods are supposed to form the accessor based on method name and signature.

    The other advantage of properties is that they act like fields syntactically, and not like methods, which has the advantage of creating more clean code.

    I'm inclined to think a get/set function is more readable than a property since it is unambiguously a function as opposed to a straight-up value.

    Most of the time properties are inlined by the Jit engine, because they are very simple, which means most of the time properties act like fields more than they act like functions, so they are closer to how fields behave than functions.

    In the case of properties it doesn't mater if there is ambiguity between a function call and field access because for the greatest part you don't pay the function call cost, property getters and setters, because of their simplicity, are high candidates for inlining, which means that cost wise the are closer to fields than function calls *.

    • Note: not all properties are cheap, but the general guidelines state that they should be as simple and lightweight as possible.

提交回复
热议问题