When to use get and set properties in C#

后端 未结 3 1640
太阳男子
太阳男子 2020-12-11 04:54

When should we use get and set properties in C#?

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 05:29

    According to the Property Usage Guidelines on MSDN:

    • Use a property when the member is a logical data member. In the following member declarations, Name is a property because it is a logical member of the class.

    • Use a method when:

      • The operation is a conversion, such as Object.ToString.
      • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
      • Obtaining a property value using the get accessor would have an observable side effect.
      • Calling the member twice in succession produces different results.
      • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
      • The member is static but returns a value that can be changed.
      • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.

提交回复
热议问题