[英]Flexible object creation in 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.");
}
}
当然有一个更优雅的方法来做到这一点......显然我可以允许客户端代码来创建对象,但我想消除使用除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.");
}
}
编辑:或者如果您希望消费者只能访问该类(因为该方法是私有的),您可以使该类具有通用性
public class MyController<TList> where TList : ListControl, new()
{
public TList ListControl { get; private set; }
}
这听起来像你可能想要使用泛型
private void InitialiseListControl<TList>() where TList : ListControl, new()
{
ListControl = new TList();
}
有关通用方法的更多信息,请参阅MSDN文档: http : //msdn.microsoft.com/en-us/library/twcad0zb(v = vs。80).aspx
请注意,本文解释了泛型方法以及如何使用where
关键字。 但它没有解释如何使用new
关键字。 new
关键字指定您提供的type参数必须具有默认构造函数 。 本文下面的评论给出了另一个使用new关键字的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.