我加載動態指定用戶控制到一個佔位符在這樣的父(用戶)控制:將用戶控件從類型名稱轉換爲自定義控件類型?
// 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
對象。
啊 - 很明顯是的,我可以,所以謝謝你<嘲笑的笑容>。我曾試圖轉換爲* WebControl *,認爲這會起作用,但得到了運行時錯誤「無法將類型爲'ASP.controls_outputchart_dundas_ascx'的對象轉換爲鍵入'System.Web.UI.WebControls.WebControl'」。 - 我沒有想到「控制」會起作用,而「WebControl」不會。無論如何,非常感謝您的支持 - 非常感謝。 –