Is using a static property in a form bad practice

2019-04-30 07:21发布

In a complex form, I have a property called Readonly that determines if everything is editable or not. 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.

标签: c# static
3条回答
beautiful°
2楼-- · 2019-04-30 07:36

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.

查看更多
Emotional °昔
3楼-- · 2019-04-30 07:38

Here is an alternative solution:

  1. Add the controls to your form as usual
  2. Create an interface called IReadOnlyToggable which has a IsReadOnly property and let the form implement it.
  3. Add the following property to your custom controls:

code:

public bool IsFormReadOnly
{
    get 
    {
        var form  = ParentForm as IReadOnlyToggable;
        return form != null && form.IsReadOnly;
    }
}
查看更多
beautiful°
4楼-- · 2019-04-30 07:44

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

查看更多
登录 后发表回答