【问题标题】:How to typecaste control dynamically?如何动态类型转换控件?
【发布时间】:2014-03-20 19:13:03
【问题描述】:

C# .net,winforms 应用程序。,Visual Studio 2010

我创建了一个控件 c,它可以是文本框或组合框。现在我想动态输入cast c,如果发件人是组合框而不是使用组合框输入c,如果发件人是文本框,则将c作为文本框。

这是执行此操作的示例代码,但我正在寻找更好的方法。

如果你有请建议..

现在我就是这样的

private void Test(Object sender, EventArgs e)
{
  Control c = sender as Textbox(); //assuming sender is textbox
  if( c== null)
 {
   c = sender as ComboBox(); // assuming sender is combobox
 }
}

 // I want better way.

例如

c = sender as Combobox() || sender as Textbox //Like this

【问题讨论】:

  • 您已将c 声明为Control,因此没有任何意义。

标签: c# winforms combobox generic-programming


【解决方案1】:

您的代码将强制转换分配给 Control 对象,因此您实际上根本不需要强制转换。你可以写:

Control c = sender as Control;

之所以可行,是因为 ComboBox 和 TextBox 都派生自 Control,并且您始终可以向上转换(“向上”指的是继承的方向)。

如果您只关心 TextBox 和 ComboBox 从 Control 继承的属性,这将非常有用。如果您需要特定于这些类型的属性,则需要进行强制转换,并分配给适当的类型:

TextBox b = sender as TextBox;
if (b != null)
{
   //Do stuff with it as a TextBox
}
else
{
    ComboBox c = sender as ComboBox;

    //You should still perform the check here as a matter of good practice.
    if (c != null)
    {
        //Do stuff with it as a ComboBox
    }
}

【讨论】:

    【解决方案2】:

    您可以使用dynamic 类型:

    private void Test(Object sender, EventArgs e)
    {
      dynamic box = sender;
      box.DoStuff(); //will throw a run-time exception if DoStuff() doesn't exist 
    } 
    

    【讨论】:

    • OP 几乎肯定会抛出异常,因为他显然是从 ComboBoxs 和 TextBoxes 调用事件。唯一安全的方法是仅访问 Control 的方法/属性,此时,为什么不直接转换为 Control?这可能是一种非常危险的方法。
    • 我假设他想调用父类中不存在的常用方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    相关资源
    最近更新 更多