c# - C#中灵活的对象创建

标签 c# asp.net

我正在创建一个包含 ListControl 对象的自定义 Web 服务器控件(扩展面板)。我希望 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.");
        }
    }

当然有更优雅的方法来做到这一点...显然我可以允许客户端代码创建对象,但我想消除使用 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.");
    }
}

关于c# - C#中灵活的对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311806/

相关文章:

c# - 从图表控件中检索 DateTime x 轴值

读取文本文件时 C# SecurityException

c# - 为什么不能在一个方法中调用两次 OpenConnection()?

c# - 点击事件中的 ajax 请求后重定向

c# - 从 C# 到 mondrian 的 AdomdConnection 连接

asp.net - Signalr中哪种WebSocket或Long Polling更好?

c# - ASP .NET C# 从 web 路径中的文件中获取所有文本

c# - 生成和打印身份证时文本模糊

c# - 简单的 LINQ/Lambda 查询未编译

c# - Asp.net core + EF Code优先,迁移不同项目中的文件