When to use properties instead of functions

后端 未结 6 1336
感情败类
感情败类 2020-11-29 01:43

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

6条回答
  •  北海茫月
    2020-11-29 02:00

    Here are Microsoft's guidelines:

    Choosing Between Properties and Methods

    • Consider using a property if the member represents a logical attribute of the type.

    • Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

    • Do use a method, rather than a property, in the following situations.

      • The operation is orders of magnitude slower than a field set would be. If you are even considering providing an asynchronous version of an operation to avoid blocking the thread, it is very likely that the operation is too expensive to be a property. In particular, operations that access the network or the file system (other than once for initialization) should most likely be methods, not properties.

      • The operation is a conversion, such as the Object.ToString method.

      • The operation returns a different result each time it is called, even if the parameters do not change. For example, the NewGuid method returns a different value each time it is called.

      • The operation has a significant and observable side effect. Note that populating an internal cache is not generally considered an observable side effect.

      • The operation returns a copy of an internal state (this does not include copies of value type objects returned on the stack).

      • The operation returns an array.

提交回复
热议问题