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

标签 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;
}

最佳答案

您可以将 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;
}

关于C#:将字符串转换为对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1380181/

相关文章:

javascript - 强制下一个界面键与前一个键具有相同的类型

function - 展开对象以作为函数参数传递

C# 强制转换为可空类型?

c# - 变量名 '@Param'已经被声明

c# - 是否有 .NET 函数来验证类名?

c# - Elasticsearch 7和Nest 7-检索结果时,我收到键值对列表或空对象列表

C# 泛型和转换问题

types - 去Go语言: Type assertion on customized type

分配给较大宽度的整数时的 C 整数溢出行为

c# - 类型转换泛型