C# 表单初始化的良好风格
你好,
我的问题是关于 C# 中良好的编程实践。如果我正在创建具有各种表单的应用程序,我将在 Load 方法内初始化与数据库的连接,或者它应该在表单的基本构造函数内?填充表单基本文本框和组合框的其他代码也可以位于 Load 方法内部,或者为此目的使用构造函数总是更好?
预先感谢,
科内尔
Possible Duplicate:
How should the Form.Load event be used compared to its constructor method?
Hello,
My question is regarding good programming practices in C#. If I'm creating a application with various forms I would initialize the connection to DB inside the Load method, or it should be inside the basic Constructor of the form? As well the other code to fill the forms basic textboxes and comboboxes can be inside the Load method or it is always better to use the constructor for that purpose?
Thanks in advance,
Kornel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每当您想要更改属于表单的控件的状态时,我建议您在表单加载事件中执行此操作。
在表单的构造函数中执行此操作很容易出错。您是否想过如果尝试在构造函数中但在
InitializeComponents()
方法调用之前执行此操作会发生什么?关于ConnectionString,您可以在两者中执行此操作,因为它与表单并不真正直接相关。
您还可以查看一些开源项目代码,看看他们如何处理
ConnectionString
或其他一些与 Form 不相关的内容:)
Whenever you want to change the state of a control that belongs to a Form, I suggest you doing this in the Form Load event.
Doing that in the constructor of the form is error prone. Have you thought about what would happen if you try to do it in the constructor, but before the
InitializeComponents()
method call?About the ConnectionString, you could do that in both, because that isn't really directly related with the Form.
You could also take a look at some open-source projects codes, to see how they do that about the
ConnectionString
or some other stuff not related with the Form:)
在站点注释上..永远不要直接在构造函数或表单加载中执行任何操作。
创建一个 init 方法或从适当的方法(构造函数、加载)调用的方法。这使得重构和单元测试变得更容易。而且代码通常更容易阅读。
On a site note.. never do anything directly in the constructor or form load.
Create a init method or something that you call from the appropriate method (constructor,load). This makes refactoring and unit testing easier.. And the code is often easier to read.
绝对最好以
Load 的形式执行
,因为这样它只会在需要时发生。但也同意使用从表单加载事件处理程序调用的 init 方法的建议。Definitely better to do in the form
Load
, because that way it will only happen when needed. But also agree with the suggestion to use an init method you call from your form load event handler.我投票支持构造函数中的连接和 Load 方法中的表单填写!
我还认为没有很大的区别......这取决于应用程序的实现!例如,您可以从基本表单继承所有表单,并将连接字符串检索逻辑放在那里。
如果你想更深入,我建议你看看依赖注入(搜索 Windsor castle、spring.net、ninject...)以在表单类中注入数据库访问类!
I vote for connection in constructor and form fill in Load method!
I think also that there is not a big difference... it depends from application implementation! For example you can inherit all your forms from a base form and put there connection string retrieve logic.
If you want to go deeper I suggest you to look at dependency injection (search for windsor castle, spring.net, ninject...) to inject database access classes inside form classes!