C# 组合框简化法

C# 组合框简化法,c#,winforms,visual-studio,C#,Winforms,Visual Studio,我有3个或更多具有相同功能的组合框。我想的是创建一个方法,然后调用它 下面是示例代码 问题:有没有办法将这5个组合框组合成1个,因为它们具有相同的功能,如果我有多个组合框,可以简化此方法 public double comboBoxTry() { double x; if (comboBox1.SelectedItem.ToString() == "First") { x = 3.5; } else if (comboBox1.SelectedItem.T

我有3个或更多具有相同功能的组合框。我想的是创建一个方法,然后调用它

下面是示例代码

问题:有没有办法将这5个组合框组合成1个,因为它们具有相同的功能,如果我有多个组合框,可以简化此方法

    public double comboBoxTry()
    { double x;
    if (comboBox1.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox1.SelectedItem.ToString() == "Second")
    { x = 4; }

    //Second ComboBox and so on
    if (comboBox2.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox2.SelectedItem.ToString() == "Second")
    { x = 4; }

if (comboBox2.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox2.SelectedItem.ToString() == "Second")
    { x = 4; }

if (comboBox3.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox3.SelectedItem.ToString() == "Second")
    { x = 4; }

if (comboBox4.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox4.SelectedItem.ToString() == "Second")
    { x = 4; }


if (comboBox5.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox5.SelectedItem.ToString() == "Second")
    { x = 4; }

// I want to Combine this  5 ComboBox  into 1 since  they have the same functionality 

    return x;
    }

    private void btnCompute_Click(object sender, EventArgs e)
        { txtResult.Text = (x * double.Parse(txtAmount.Text)).ToString(); }

如果我理解正确,在引发事件时,您希望调用comboBoxTry

如果这是你想做的,你不必这么做。您可以在EventHandle中执行此操作,在comboBox.Name上打开一个开关,然后执行测试

private void btnCompute_Click(object sender, EventArgs e)
    { 
        double x = 0;
        switch (sender.name)
        {
            case "CombOne" :
             [Your tests]
             break;
            case "Combtwo" :
            ....
            ....
        }
        txtResult.Text = (x * double.Parse(txtAmount.Text)).ToString(); 
}
编辑:对于最后一次编辑,我认为可以使用标记属性。使用相同的行为标记所有组合框,然后在标记上进行测试

这样你就可以

private void btnCompute_Click(object sender, EventArgs e)
        { 
            double x = 0;
            if (sender.tag == "SameBehaviorComboBox")
            {
                if (sender.SelectedItem.ToString() == "First")
                { 
                    x = 3.5; 
                }
                else if (sender.SelectedItem.ToString() == "Second")
                { 
                    x = 4; 
                }
            }
            txtResult.Text = (x * double.Parse(txtAmount.Text)).ToString(); 
    }

它适用于所有具有相同标签的组合框。

您的问题是什么?这就是您使用的逻辑吗?还有,这个代码在哪里?在事件处理程序中?您的帖子实际上缺少问题本身。试着详细说明一下。有没有办法简化代码?比如说,如果我有多个组合框snewbiev,你需要解释一下你在这里做什么。。这两个组合框是在一个面板中吗?它们都有相同的元素吗?您可以创建一个方法
GetXFromComboBox(ComboBox cb)
,但如果没有更多信息,还不清楚如何提供帮助。此外,您提供的代码甚至没有编译,因为
x
与您的单击事件处于不同的范围内