限制基类参数的类型

Joh*_*ona 4 c# .net-4.0 winforms

我有这样的代码:

public static void ToUpperCase(params Control[] controls)
{
    foreach (Control oControl in controls)
    {
        if (oControl is TextBox)
        {
            oControl.TextChanged += (sndr, evnt) =>
            {
                TextBox txtControl = sndr as TextBox;
                int pos = txtControl.SelectionStart;
                txtControl.Text = txtControl.Text.ToUpper();
                txtControl.SelectionStart = pos;
            };
        }
        else if (oControl is ComboBox)
        {
            oControl.TextChanged += (sndr, evnt) =>
            {
                ComboBox cmbControl = sndr as ComboBox;
                int pos = cmbControl.SelectionStart;
                cmbControl.Text = cmbControl.Text.ToUpper();
                cmbControl.SelectionStart = pos;
            };
        }
        else throw new NotImplementedException(oControl.GetType().DeclaringType.ToString() + " is not allowed.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我想限制params Control[] controls只接受一个TextBox和一个ComboBox类型.

我的代码在C#,框架4,在VS2010Pro中构建,项目在WinForms中.

请帮忙.提前致谢.

Chr*_*ain 5

你不能 - 他们没有一个好的共同祖先.

你可以(也可能应该)做的是对你的方法进行两次重载,它们带有每个参数:

public static void ToUpperCase(params TextBox[] controls)
{
    foreach (TextBox oControl in controls)
        oControl.TextChanged += (sndr, evnt) =>
        {
            TextBox txtControl = sndr as TextBox ;
            int pos = txtControl.SelectionStart;
            txtControl.Text = txtControl.Text.ToUpper();
            txtControl.SelectionStart = pos;
        };
}

public static void ToUpperCase(params ComboBox[] controls)
{
    foreach (ComboBoxControl oControl in controls)
        oControl.TextChanged += (sndr, evnt) =>
        {
            ComboBox txtControl = sndr as ComboBox;
            int pos = txtControl.SelectionStart;
            txtControl.Text = txtControl.Text.ToUpper();
            txtControl.SelectionStart = pos;
        };
}
Run Code Online (Sandbox Code Playgroud)

  • 仿制药真的需要吗?假设TControl应该是基本控件,将参数声明为Control将实现相同的功能?,Control无论如何都不实现SelectionStart所以仍然需要在AddTextChangedHandler中处理TextBoxes或ComboBoxes的条件获取/设置SelectionStart.除非要添加更常见的复杂性,否则我不确定是否值得尝试使用常用函数来添加此处理程序. (3认同)
  • 是的,非常正确.这是我能想到的两个最佳答案. (2认同)