Jon*_*eet 11
当然 - 只需使用基类型作为泛型类型参数创建一个列表:
List<Control> controls = new List<Control>();
controls.Add(new TextBox());
controls.Add(new Label());
controls.Add(new Button());
// etc
Run Code Online (Sandbox Code Playgroud)
请注意,当您再次检索项目时,您只会"知道"它们作为基本类型,因此如果要执行任何特定于子类型的操作,则需要进行转换.例如:
// Assuming you know that there's at least one entry...
Control firstControl = controls[0];
TextBox tb = firstControl as TextBox;
if (tb != null)
{
// Use tb here
}
Run Code Online (Sandbox Code Playgroud)
如果要获取特定类型(或其子类型)的所有元素,可以使用以下OfType<>
方法:
foreach (TextBox tb in controls.OfType<TextBox>())
{
// Use tb here
}
Run Code Online (Sandbox Code Playgroud)