编程语言
首页 > 编程语言> > [Professional C# 7] Use of Properties and Methods

[Professional C# 7] Use of Properties and Methods

作者:互联网

➤ Client code should be able to read its value. Write-only properties are not recommended, so, for exam-
ple, use a SetPassword method, not a write-only Password property.
➤ Reading the value should not take too long. The fact that something is a property usually suggests that
reading it will be relatively quick.
➤ Reading the value should not have any observable and unexpected side effect. Furthermore, setting the
value of a property should not have any side effect that is not directly related to the property. Setting
the width of a dialog has the obvious effect of changing the appearance of the dialog on the screen.
That’s fine, because that’s obviously related to the property in question.
➤ It should be possible to set properties in any order. In particular, it is not good practice when setting a
property to throw an exception because another related property has not yet been set. For example, to
use a class that accesses a database, you need to set ConnectionString, UserName, and Password,
and then the author of the class should ensure that the class is implemented such that users can set
them in any order.
➤ Successive reads of a property should give the same result. If the value of a property is likely to change
unpredictably, you should code it as a method instead. Speed, in a class that monitors the motion of
an automobile, is not a good candidate for a property. Use a GetSpeed method here; but Weight and
EngineSize are good candidates for properties because they will not change for a given object.

标签:Use,set,C#,class,value,should,Professional,property,any
来源: https://www.cnblogs.com/FH-cnblogs/p/16408175.html