我有一个页面,我必须根据用户选择动态加载控件.让我们说我有这样的事情:
public static readonly DictionaryDynamicControls = new Dictionary { { "UserCtrl1", "~/Controls/UserCtrl1.ascx" }, { "UserCtrl2", "~/Controls/UserCtrl2.ascx" }, { "UserCtrl3", "~/Controls/UserCtrl3.ascx" }, { "UserCtrl4", "~/Controls/UserCtrl4.ascx"} };
现在让我们说,而不是在加载控件的页面上,代码是这样的:
protected void Page_Load(object sender, EventArgs e) { SomePanel.Controls.Add(GetControl()); } private Control GetControl() { string dynamicCtrl = CurrentItem.DynamicControl; string path = SomeClass.DynamicControls[dynamicCtrl]; Control ctrl = null; //TODO: find a better way to load the controls switch (dynamicCtrl) { case "UserCtrl1": { ctrl = (UserCtrl1)LoadControl(path); } break; case "UserCtrl2": { ctrl = (UserCtrl2)LoadControl(path); } break; case "UserCtrl3": { ctrl = (UserCtrl3)LoadControl(path); } break; default: { throw new ApplicationException("Invalid dynamic control added."); } } return ctrl; }
该页面具有所需的注册语句.知道我怎么能摆脱这个丑陋的开关声明?
您不需要从LoadControl转换结果.
这应该做:
private Control GetControl() { string dynamicCtrl = CurrentItem.DynamicControl; string path = SomeClass.DynamicControls[dynamicCtrl]; Control ctrl = LoadControl(path); return ctrl; }