本文介绍了何时使用属性而不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能是个人喜好的问题,但是你何时在代码中使用属性而不是函数
This is probably a matter of personal preference, but when do you use properties instead of functions in your code
例如,为了得到一个错误日志,我可以说
For instance to get an error log I could say
string GetErrorLog()
{
return m_ErrorLog;
}
或我可以
string ErrorLog
{
get { return m_ErrorLog; }
}
如何决定使用哪一个?我似乎在我的用法不一致,我在寻找一个很好的一般规律。感谢。
How do you decide which one to use? I seem to be inconsistent in my usage and I'm looking for a good general rule of thumb. Thanks.
推荐答案
如果以下情况属实,我倾向于使用属性:
I tend to use properties if the following are true:
- 该属性将返回单个逻辑值
- 很少或没有涉及逻辑(通常只返回一个值,值)
如果以下情况属实,我倾向于使用方法:
I tend to use methods if the following are true:
- 返回值将涉及到重要的工作 - 即:它将从数据库获取,或可能需要时间的东西
此外,我建议您查看。他们建议:
In addition, I'd recommend looking at Microsoft's Design Guidelines for Property Usage. They suggest:
在以下情况下使用方法:
Use a method when:
- 操作是一种转换,例如Object.ToString。
- 此操作非常昂贵,您希望与用户进行沟通,以便他们考虑缓存结果。
- 获取属性
- 连续两次调用成员会产生不同的结果。
- 执行顺序很重要。请注意,类型的属性应该能够以任何顺序设置和检索。
- 成员是静态的,但返回可以更改的值。
- 成员返回一个数组。返回数组的属性可能会非常误导。通常需要返回内部数组的副本,以便用户不能更改内部状态。这,加上用户可以容易地认为它是索引属性的事实,导致低效的代码。在下面的代码示例中,每次调用Methods属性都会创建一个数组副本。因此,将在以下循环中创建2n + 1个副本的数组。
- 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.
这篇关于何时使用属性而不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!