开发者

Best place to create windows form objects

I'm creating a windows app in c# 2008 that will have around 8-10 dialog boxes. I want these forms to exist throughout the life of the program. Where's the best place to create and store the objects?

I'm coming from Delphi, where Form objects were usually stored in global variables.

I'm tempted to do it in the static Program class. Should I put them in 开发者_如何学Gothe main form instead?

Thanks for helping a C# newb out.


Why do you want these dialog boxes to exist throughout the life of the program? In general, dialog boxes are created when they're needed, get used, then are destroyed. If you need to display it again, you create a new one and use it.

If you have a legitimate reason to keep them around, then that's fine, but don't use the Program class for this. I'm assuming that your application has a main form that all others get launched from. If this is the case, make them instance variables on that form and use them from there.


Forms are expensive objects, they have a lot of internal state. Caching makes sense if creating the data is expensive. Forms behave the exact opposite, creating their data is cheap. Using cached data becomes expensive when Windows has swapped out the data to the paging file. Which is very likely to happen in your case, the dialogs wouldn't be used very frequently. It actually takes longer to show the dialog.

If your data to fill the dialog is expensive to create then cache that data, not the form.


In generaly, there is no reason to store the dialogs for reusing. The typical scenario is:

using( MyDialog dlg = new MyDialog() ) {
    dlg.MyTextProperty = "Are you realy sure, you want do XY operation?";
    dlg.MyNumberProperty = 15;

    DialogResult rslt = dlg.ShowDialog( this ); // the "this" is current form or control
    if ( rslt == DialogResult.OK ) {
        object userInput = dlg.UserInput;
        // do what you want with user input
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜