C#:将字符串转换为对象引用

1 c# types casting

基本上,按钮的标签属性是我需要动态引用的现有组合框的名称.它是处理多个按钮的通用功能.救命

private void SQLButton(object sender, EventArgs e)
{
    magic(((Button)sender).Tag.ToString());
}

private void magic(string currentcombo)
{
    string CurrentText = (ComboBox).(currentcombo).Text;
}
Run Code Online (Sandbox Code Playgroud)

Aus*_*nen 6

您可以将Tag属性设置为实际的ComboBox,并完全避免您的问题.

//code when defining your button...
{
     sqlButton.Tag = comboBoxA;  //instead of comboBoxA.Name
}

private void SQLButton(object sender, EventArgs e)
{
    Button button = sender as Button;
    ComboBox comboBox = button.Tag as ComboBox;

    if (comboBox == null ) 
    {...}
    else
    {
        magic(comboBox);
    }
}

private void magic(ComboBox currentcombo)
{
    string CurrentText = currentcombo.Text;
}
Run Code Online (Sandbox Code Playgroud)