Net Core教程

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

这篇关于[Professional C# 7] Use of Properties and Methods的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!