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

前端 未结 15 1757
自闭症患者
自闭症患者 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条回答
  •  梦毁少年i
    2020-12-25 15:28

    Two big advantages to properties:

    • They can be shown and edited in the Property Grid. Without properties, how would you know which methods to show editors for?
    • They offer a hint that something is cheap to read and write, and that reading it causes no side effects. (It's possible to violate that, of course, but by making something a property, you're declaring that that's your intent.) Therefore, the debugger can take that hint. If you hover the mouse over a property, the debugger will show its value in a tooltip. It wouldn't make sense to do the same thing for any possible method; too easy to accidentally do something with side effects.

提交回复
热议问题