【问题标题】:Inherited Windows Form strange behaviour继承 Windows 窗体的奇怪行为
【发布时间】: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


【解决方案1】:

还有另一个question 解决了类似的问题。此外,接受的答案提供了克服此行为的解决方案:https://stackoverflow.com/a/2427420/674700。

基本上,在您的情况下,添加 DesignTimeHelper 类并使用以下修改来查看差异:

private void BaseForm_Load(object sender, EventArgs e)
{
    if (!DesignTimeHelper.IsInDesignMode)
    {
        if (!IsUserValid())
        {
            MessageBox.Show("User is not valid");
        }
    }
    else
    {
        MessageBox.Show("Called from VS");
    }
}

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多