gpt4 book ai didi

c# - 何时使用属性而不是函数

转载 作者:IT王子 更新时间:2023-10-29 03:53:06 25 4
gpt4 key购买 nike

这可能是个人喜好问题,但是什么时候在代码中使用属性而不是函数

例如获取错误日志我可以说

string GetErrorLog()
{
return m_ErrorLog;
}

或者我可以

string ErrorLog
{
get { return m_ErrorLog; }
}

您如何决定使用哪一个?我的用法似乎不一致,我正在寻找一个好的一般经验法则。谢谢。

最佳答案

如果满足以下条件,我倾向于使用属性:

  • 该属性将返回一个单一的逻辑值
  • 涉及很少或没有逻辑(通常只是返回一个值,或者做一个小的检查/返回值)

如果满足以下条件,我倾向于使用方法:

  • 返回值将涉及大量工作 - 即:它将从数据库中获取,或者可能需要“时间”的东西
  • 获取或设置值涉及很多逻辑

此外,我建议查看 Microsoft's Design Guidelines for Property Usage .他们建议:

Use a property when the member is a logical data member.

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.

关于c# - 何时使用属性而不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1374273/

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