gpt4 book ai didi

c# - 限制基类参数的类型

转载 作者:太空狗 更新时间:2023-10-30 00:08:23 25 4
gpt4 key购买 nike

我有这样的代码:

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.");
}
}

我想限制 params Control[] 控件 只接受一个 TextBox 和一个 ComboBox 类型。

我的代码是C#,framework 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;
};
}

关于c# - 限制基类参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com