我正在创建一个包含ListControl对象的自定义Web服务器控件(扩展Panel).我希望ListControl类型是灵活的,即允许在aspx标记中指定ListControl的类型.目前我正在检查用户的选择并使用switch语句初始化控件:
public ListControl ListControl { get; private set; }
private void InitialiseListControl(string controlType) {
switch (controlType) {
case "DropDownList":
ListControl = new DropDownList();
break;
case "CheckBoxList":
ListControl = new CheckBoxList();
break;
case "RadioButtonList":
ListControl = new RadioButtonList();
break;
case "BulletedList":
ListControl = new BulletedList();
break;
case "ListBox":
ListControl = new ListBox();
break;
default:
throw new ArgumentOutOfRangeException("controlType", controlType, "Invalid ListControl type specified.");
}
}
Run Code Online (Sandbox Code Playgroud)
当然有更优雅的方法来做到这一点......显然我可以允许客户端代码来创建对象,但我想消除使用除aspx标记之外的任何代码的需要.任何建议,将不胜感激.谢谢.
我很困惑为什么这个代码不能编译,如果listControl
是ListControl对象,如DropDownList:
foreach (var item in listControl.Items) {
item.Value = string.empty;
}
Run Code Online (Sandbox Code Playgroud)
编译器认为item
是类型object
.如果我替换var
为ListItem
明确声明变量,它的工作原理.该Items
属性是一个ListItemCollection
,实现IEnumerable
.编译器是否应该能够告诉集合中的对象是否为类型ListItem
?