小编kad*_*d81的帖子

C#中的灵活对象创建

我正在创建一个包含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标记之外的任何代码的需要.任何建议,将不胜感激.谢谢.

c# asp.net

4
推荐指数
1
解决办法
296
查看次数

为什么必须在foreach C#中显式声明ListItem

我很困惑为什么这个代码不能编译,如果listControl是ListControl对象,如DropDownList:

foreach (var item in listControl.Items) {
    item.Value = string.empty;
}
Run Code Online (Sandbox Code Playgroud)

编译器认为item是类型object.如果我替换varListItem明确声明变量,它的工作原理.该Items属性是一个ListItemCollection,实现IEnumerable.编译器是否应该能够告诉集合中的对象是否为类型ListItem

c# asp.net

3
推荐指数
1
解决办法
298
查看次数

标签 统计

asp.net ×2

c# ×2