【发布时间】:2013-02-13 23:32:01
【问题描述】:
在加载表单时,我需要检查X 数量以确定是否打开或关闭表单。下面是一个简单的例子。
public partial class BaseForm : Form
{
private void BaseForm_Load(object sender, EventArgs e)
{
if(!IsUserValid())
MessageBox.Show("User is not valid");
}
private bool IsUserValid()
{
List<string> allowedUsernames = new List<string>();
using (SqlConnection con = new SqlConnection(_connectionString))
{
//Get a list of usernames, none of which are "Developer" usernames
}
return allowedUsernames.Any(username => username == Environment.UserName);
}
}
public partial class DerivedForm : BaseForm
{
}
上面的例子,无论我的用户名如何,我都可以在设计器中完美地加载表单。如果我做另一个表单 DerivedForm 并继承 base 然后它调用 Load 并因此将显示 MessageBox 然后 Close 在设计模式下的表单不允许我访问设计器,为什么派生的WindowsForm 需要使用Load 事件,但基础不需要?如果您正在使用 WindowsForms 进行继承,那么不使用 Load 事件是否明智?
我只是觉得这很奇怪,有人知道吗?
【问题讨论】:
-
我没有看到
override。你在哪里挂钩加载事件? -
@P.Brian.Mackey 没有
override只是从派生到基类的直接继承。 -
考虑将业务逻辑与 UI 分离。表单不应包含名为
IsUserValid的方法 - 将其移至引擎类并在其上调用它,然后根据结果决定是否创建(并显示)表单。 -
@BojanKomazec 我知道我应该把我的逻辑放在一个类中,这样做只是为了示例代码的简单性和复制问题。
-
“考虑将业务逻辑与 UI 分离”,还可以考虑使用实际上允许这种事情的框架,例如 WPF。
标签: c# winforms inheritance