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中.
请帮忙.提前致谢.
你不能 - 他们没有一个好的共同祖先.
你可以(也可能应该)做的是对你的方法进行两次重载,它们带有每个参数:
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)