我想轉換的(這是很容易出錯)....通型的類型,而不是字符串paramater
public static void GenerateReport(string report)
{
switch (report)
{
case "ReportA":
// do stuff
break;
case "ReportB":
// do stuff
break;
case "ReportC":
// do stuff
break;
}
}
對此....
public static void GenerateReport<T>()
{
switch (T) // BUT.... how do I handle this?
{
case ReportA:
// do stuff
break;
case ReportB:
// do stuff
break;
case ReportC:
// do stuff
break;
}
}
我所看到的很多問題都詢問差不多是同樣的事情,但他們都沒有讓我回答。像this one,但對我而言,該線程提供的解決方案不起作用。當我嘗試編譯時會引發多個語法錯誤。該解決方案有云:
switch typeof(T) {
//
}
使有問題的類型處理「做東西」部分。基本上把你的'switch'改成OOP設計。 – juharr
不知道我關注 –
這基本上是多態。創建一個具有'GenerateReport()'方法的抽象'Report'類。 – Amy