【问题标题】:Call method on derived form from the base form从基本形式调用派生形式的方法
【发布时间】:2013-09-03 20:32:23
【问题描述】:

我一直在尝试使用 Visual Inheritance,以便可以在多种形式中重复使用一组按钮。

基本上我想要实现的是,我希望按钮在不同的表单中具有相同的视觉行为,但是,它们应该根据继承它的表单执行不同的操作。

假设我在FormButtonBar 中有以下按钮

新 |编辑 |搜索 |取消 |关闭

它们应该被禁用或根据当前情况更改其文本和图标(我使用.Tag 这样做),这些是显示的替代选项

保存 |保存 |删除 |取消 |关闭

即使我在继承它的表单上按预期工作,我显然希望这些按钮根据我拥有的表单处理不同的内容。

我想到的是一种调用像saveNewItem()saveChangedItem()removeItem()这样的方法的方法,每个继承FormButtonBar的表单都应该有。

但是我如何从FormButtonBar 给他们打电话呢?

例如:

    private void buttonSearchRemove_Click(object sender, EventArgs e)
    {

        if (buttonSearchRemove.Tag == "search")
        {

            //call the search form here and wait for something to be returned

            //the following 3 lines are the ones that switch text, icons and enabled/disabled on the buttons

            utils.hablitarBotoes(panelBotoes, "abc");
            utils.alternarBotoes(panelBotoes, "b");
            buttonBuscarExcluir.Text = "Excluir";

        }
        else if (buttonSearchRemove.Tag == "remove")
        {
            DialogResult reply = MessageBox.Show("Are you sure you want to remove it?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (reply == DialogResult.Yes)
            {

                  //CALL REMOVE METHOD THAT SHOULD BE IN THE FORM INHERITING THIS ONE, BUT HOW?

                  removeItem();

              }

                utils.hablitarBotoes(panelBotoes, "nbf");
                utils.alternarBotoes(panelBotoes, "");

                buttonNovoSalvar.Text = "New";
                buttonBuscarExcluir.Text = "Search";
                buttonAlterarSalvar.Text = "Edit";
            }
        }

【问题讨论】:

  • 您应该在基类中声明所有方法(您提到的)并在派生类中覆盖这些方法。
  • 但是如果我这样做了,我会不会丢失我在基类中实现的用于切换文本和图标的代码,最终不得不以派生形式重新实现它们?

标签: c# inheritance visual-inheritance


【解决方案1】:

您应该在基类中将这些方法声明为虚拟方法,然后在子类中覆盖它们。

public class MyBaseClass
{
    public virtual void RemoveItems()
    {
    }
}

public class MyDerivedClass : MyBaseClass 
{
    public override void RemoveItems()
    {
       //your specific implementation for this child class
    }
}

【讨论】:

  • 我想那行得通!我现在不在家,我会尽快测试。非常感谢!
猜你喜欢
  • 2011-07-05
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 2014-03-17
相关资源
最近更新 更多