gpt4 book ai didi

.net - 是否应该将所有具有返回值的方法都转换为属性?

转载 作者:行者123 更新时间:2023-12-01 07:47:41 26 4
gpt4 key购买 nike

我只是在想它,因为 .Net 引入了属性,所以在这种情况下,您是否希望将代码作为返回值的方法而不是只读属性。

最佳答案

不。我建议您查看 Microsoft's Property Usage Guidlines :

Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data. Use the following guidelines to help you choose between these options.

  • 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.

关于.net - 是否应该将所有具有返回值的方法都转换为属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2866444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com