我正在创建一个包含listcontrol对象的自定义web服务器控件(extends panel)。我希望ListDe控件类型是灵活的,即允许在ASPX标记中指定ListMype的类型。目前我正在检查用户的选择,并使用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.");
        }
    }

当然有一个更优雅的方法来做这件事…显然,我可以允许客户端代码创建对象,但我想消除使用aspx标记以外的任何代码的需要。如有任何建议,将不胜感激。谢谢。

最佳答案

你可以用字典:

Dictionary<string, Type> types = new Dictionary<string, Type>();
types.Add("DropDownList", typeof(DropDownList));
...

private void InitialiseListControl(string controlType)
{
    if (types.ContainsKey(controlType))
    {
        ListControl = (ListControl)Activator.CreateInstance(types[controlType]);
    }
    else
    {
        throw new ArgumentOutOfRangeException("controlType", controlType, "Invalid ListControl type specified.");
    }
}

但是如果你想变得更灵活,你可以绕过字典,使用一点反射:
private void InitialiseListControl(string controlType)
{
    Type t = Type.GetType(controlType, false);
    if (t != null && typeof(ListControl).IsAssignableFrom(t))
    {
        ListControl = (ListControl)Activator.CreateInstance(t);
    }
    else
    {
        throw new ArgumentOutOfRangeException("controlType", controlType, "Invalid ListControl type specified.");
    }
}

09-18 17:54