简体   繁体   中英

Cast user-control to custom control type from type name?

I am loading a dynamically specified user control into a place-holder in the parent (user) control like this:

// 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);

Clearly it would be nicer not to have to explicitly cast the _chartControl variable each time -- is there a cleaner way? Each user control implements the IOutputChart interface; however, I can't use that directly because Controls.Add() expects a Control object.

您不仅可以将所有这些转换为Control吗?

phChart.Controls.Add((Control)_chartControl);

I assume all of your controls derive from Control base class. Then why don't you cast the _chartControl to Control and add it.

_chartControl = (Control)LoadControl(chartClassName + ".ascx");
phChart.Controls.Add(_chartControl);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM