Pass ComboBox Selected Item as Method Parameter

前端 未结 2 1044
野性不改
野性不改 2021-01-27 10:48

What\'s the proper way to pass a ComboBox Selected Item as a Method Parameter?

Or is there even any advantage to doing this?

I have limited experience in program

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 11:27

    To get the Selected Item's string you need to call ToString(). Then you can pass the string to any method instead of an object. That being said, you can create a Dictionary to easily get the opposite color using the selected item's name instead of using if/else or switch statements:

    private static Dictionary _oppositesDictionary = new Dictionary()
    {
        {"Green", "Red"},
        {"Orange", "Blue"},
        {"Yellow", "Purple"},
        {"Red", "Green"},
        {"Blue", "Orange"},
        {"Purple", "Yellow"}
    };
    

    Usage:

    public string OppositeColor(string color)
    {
        //No need to check if key exists
        return _oppositesDictionary[color];
    }
    
    
    
    private void button_Click(object sender, RoutedEventArgs e)
    {
        string color = cboColors.SelectedItem.ToString();
    
        MessageBox.Show(OppositeColor(color));
    }
    

    Update:

    If you want to perform small tasks based on the color name, use a switch statement.

    If you want to perform different tasks (no repeating code!) based on the color name, you might want to create a Dictionary> or Dictionary> if you want to return a value.
    Because you have only shown us an example of what you want, I can only think that this is an overkill:

    //Methods have to be static when using a field initializer
    //Func returns a string and has no paramters
    private static Dictionary> _colorFunc = new Dictionary>()
    {
        {"Green", GreenFunc},
        {"Orange", BlueFunc}
        ....
    };
    
    private static string GreenFunc()
    {
        // green logic
        return "Red";
    }
    
    //Usage
    public string OppositeColor(string color)
    {
        return _colorFunc[color]();
    }
    

提交回复
热议问题