简体   繁体   中英

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

  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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM