将未知类型的Object传递给函数

时间:2015-10-30 11:52:43

标签: c# winforms

所以这是我的代码:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (listBox1.SelectedItem.ToString()=="Light" && Form.ActiveForm.Name != "Light")
        {
            Light o = new Light();
            o.Show();
            o.listBox1.SelectedIndex = listBox1.SelectedIndex;
            NeedsToClose = false;
            this.Close();
        }
        else if(listBox1.SelectedItem.ToString() == "Acceleration"&& Form.ActiveForm.Name !="Acceleration")
        {
            Acceleration o = new Acceleration();
            o.Show();
            o.listBox1.SelectedIndex = listBox1.SelectedIndex;
            NeedsToClose = false;
            this.Close();
        }

    }

它有效,但正如你所看到的,我在这两种情况下都有这部分代码:

o.Show();
o.listBox1.SelectedIndex = listBox1.SelectedIndex;
NeedsToClose = false;
this.Close();

我想使它成为函数(void),将对象传递给它,并获得结果。有什么想法可以做到这一点?

两种表格都来自名为Template的表单,该表单派生自Form。

2 个答案:

答案 0 :(得分:2)

有两种方法可以实现此功能 - 静态输入和动态输入。

以静态类型的方式,您可以创建一个涵盖LightAcceleration表单之间共性的界面 - 具体来说,它们都有listBox1这一事实。这将让C#在编译时检查所述共性的存在。假设基类形式Template具有listBox1,您可以这样做:

Template nextForm;
if (listBox1.SelectedItem.ToString()=="Light" && Form.ActiveForm.Name != "Light") {
    nextForm = new Light();
} else if(listBox1.SelectedItem.ToString() == "Acceleration"&& Form.ActiveForm.Name !="Acceleration") {
    nextForm = new Acceleration();
}
nextForm.Show();
nextForm.listBox1.SelectedIndex = listBox1.SelectedIndex;
NeedsToClose = false;
this.Close();

在动态类型的解决方案中,让C#跳过检查,并了解如果公共部分不存在,程序将在运行时失败。除了使用关键字dynamic代替公共类型的名称外,解决方案与上述解决方案相同:

dynamic nextForm;
... // the rest is the same

答案 1 :(得分:1)

我想改进几点@dasblinkenlight回答,

{
    Template nextForm = GetForm();
    if(nextForm == null)
       return; // throw exception otherwise

    ShowNextForm(nextForm);
    NeedsToClose = false;
    this.Close();
}

private Template GetForm()
{
    string selectedItem = listBox1.SelectedItem.ToString();
    string activeFormName = Form.ActiveForm.Name;
    Template nextForm;
    if (selectedItem =="Light" && activeFormName != "Light") {
        nextForm = new Light();
    } else if(selectedItem == "Acceleration"&& activeFormName !="Acceleration") {
        nextForm = new Acceleration();
    }
    return nextForm;
}

private Template ShowNextForm(Template nextForm)
{
    nextForm.Show();
    nextForm.listBox1.SelectedIndex = listBox1.SelectedIndex;
}
相关问题