[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.
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步