[英]Cast user-control to custom control type from type name?
我正在将动态指定的用户控件加载到父(用户)控件中的占位符中,如下所示:
// dynamically load instance of chosen chart control
string chartClassName = ConfigurationManager.AppSettings["ChartControlClass"];
_chartControl = (IOutputChart)LoadControl(chartClassName + ".ascx");
// add to place-holder
if (chartClassName == "OutputChart_Dundas") phChart.Controls.Add((OutputChart_Dundas)_chartControl);
else if (chartClassName == "OutputChart_Microsoft") phChart.Controls.Add((OutputChart_Microsoft)_chartControl);
else if (chartClassName == "OutputChart_Telerik") phChart.Controls.Add((OutputChart_Telerik)_chartControl);
显然, _chartControl
每次都显式地_chartControl
变量会更好-是否有更干净的方法? 每个用户控件都实现IOutputChart
接口; 但是,我不能直接使用它,因为Controls.Add()
需要一个Control
对象。
您不仅可以将所有这些转换为Control
吗?
phChart.Controls.Add((Control)_chartControl);
我假设您所有的控件都派生自Control
基类。 然后,为什么不将_chartControl
为Control
并添加它呢?
_chartControl = (Control)LoadControl(chartClassName + ".ascx");
phChart.Controls.Add(_chartControl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.