[英]Is using a static property in a form bad practice knowing that there's only one instance of the form?
In a complex form, I have a property called Readonly
that determines if everything is editable or not. 在一个复杂的形式中,我有一个名为Readonly
的属性,它确定是否所有内容都是可编辑的。 So far, I'm passing this property to every sub custom control in this form by constructor, and in other places, I access the form itself to get the value. 到目前为止,我通过构造函数将此属性传递给此表单中的每个子自定义控件,在其他地方,我访问表单本身以获取值。
But this is quickly becoming too complex. 但这很快变得太复杂了。
I'm thinking of making this property Static in the form knowing that there's only one instance of this form in the application. 我正在考虑将这个属性设置为静态 ,知道应用程序中只有这个表单的一个实例。
Is it OK to use this property as a static in this case? 在这种情况下,可以将此属性用作静态吗? Or it's a bad practice even there's only one instance of the form. 或者这是一个不好的做法,即使只有一个表格实例。
Even if your have a single instance of the form using a static field doesn't make it safe. 即使您使用静态字段拥有单个表单实例也不会使其安全。 You could have multiple threads that cause problems. 您可能有多个导致问题的线程。 Not to mention the difficulty to unit test your application. 更不用说对您的应用程序进行单元测试的难度。 Personally I try to avoid static fields as much as possible. 我个人尽量避免使用静态字段。
Simply ask yourself: does this relate to the form or to the type of form. 简单地问自己:这确实涉及到窗体或窗体的类型 。 Hypothetically, if there were more than one form - would they all be readonly/not at the same time? 假设,如果有多个表格 - 它们是否只是同时读取/不同时? Or would it be per form? 或者是每个表格?
Then: you have the answer. 然后:你有答案。 I suspect it should be instance (non-static). 我怀疑它应该是实例(非静态)。
Here is an alternative solution: 这是一个替代解决方案:
IReadOnlyToggable
which has a IsReadOnly
property and let the form implement it. 创建一个名为IReadOnlyToggable
的接口,它具有IsReadOnly
属性并让表单实现它。 code: 码:
public bool IsFormReadOnly
{
get
{
var form = ParentForm as IReadOnlyToggable;
return form != null && form.IsReadOnly;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.