我已經定義像這樣一個工廠:如何動態地將類型傳遞給一個通用工廠?
public IPopulator CreatePopulator<T>(ReportItem Item) where T : IReportElement
{
if (typeof(T) == typeof(BarChartElement))
{
return BarChartPopulator.Create(Item);
}
else
{
throw new NotSupportedException(string.Format("Type: {0} is not suppported by {1}", typeof(T).Name, this.GetType().Name));
}
}
在調用此方法我有一個這樣的變量的類:如何
IReportElement MyElement { get; set; }
假設MyElement被實例化,以實現IReportElement一個類型,我可以使用這個變量調用我的工廠嗎?
我已經試過
Type VariableType = MyChartElement.GetType();
PopulatorFactory.CreatePopulator<VariableType>(new Chart());
而且
PopulatorFactory.CreatePopulator<MyVariable.GetType()>(new Chart());
我可以寫一個switch語句,但我覺得應該有一些辦法,我通過我的類型。這可能嗎 ?
這是可能的反思。這是你的情況的一個選項? –
反射是一個選項。 – BentOnCoding
我認爲這是[如何使用反射調用通用方法]的副本(http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method)。 –