C# 是否从类型名称将用户控件强制转换为自定义控件类型?

C# 是否从类型名称将用户控件强制转换为自定义控件类型?,c#,user-controls,casting,C#,User Controls,Casting,我正在将动态指定的用户控件加载到父用户控件的占位符中,如下所示: // dynamically load instance of chosen chart control string chartClassName = ConfigurationManager.AppSettings["ChartControlClass"]; _chartControl = (IOutputChart)LoadControl(chartClassName + ".ascx"); // add to place-

我正在将动态指定的用户控件加载到父用户控件的占位符中,如下所示:

// 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变量,有更干净的方法吗?每个用户控件实现IOutputChart接口;但是,我不能直接使用它,因为Controls.Add需要一个控件对象。

您不能将所有这些都转换为Control吗


你能不能把所有这些都转换成控制


我假设所有控件都派生自控件基类。那么为什么不将_chartControl转换为Control并添加它呢

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

我假设所有控件都派生自控件基类。那么为什么不将_chartControl转换为Control并添加它呢

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

啊-显然是的,我能,所以谢谢你。我曾尝试强制转换为WebControl,认为这会起作用,但出现运行时错误,无法将类型为“ASP.controls\u outputchart\u dundas\u ascx”的对象强制转换为类型为“System.Web.UI.WebControl.WebControl”。-我没有想到控件会工作,而网络控件不会。非常感谢你这么快就来了,无论如何-非常感谢。啊-显然是的,我可以,所以谢谢你。我曾尝试强制转换为WebControl,认为这会起作用,但出现运行时错误,无法将类型为“ASP.controls\u outputchart\u dundas\u ascx”的对象强制转换为类型为“System.Web.UI.WebControl.WebControl”。-我没有想到控件会工作,而网络控件不会。无论如何,非常感谢您的快速回复,非常感谢。事实上,非常感谢您,请参阅上面的评论,以解释我第一次明显缺乏努力的原因!不过,我实际上需要_chartControl变量作为IOutputChart对象。没问题。您仍然可以使用_chartControl作为IOutputChart对象,即使_chartControl的类型是Control。确实-非常感谢,请参阅上面的注释,以解释我第一次明显缺乏努力的原因!不过,我实际上需要_chartControl变量作为IOutputChart对象。没问题。您仍然可以使用_chartControl作为IOutputChart对象,即使_chartControl的类型是Control。