2017-01-16 90 views
1
Type T; 

if (report.ReportType == 0) { 
    T = typeof(ReportTempHum); 
} else if (report.ReportType == 11){ 
    T = typeof(ReportVibration); 
} 

List<(Type)T> result = new List<(Type)T>(); 

我想根據reportType條件將類型指定到列表中。但有些錯誤。指定一個類型.net

我該怎麼做?

在此先感謝!

編輯:錯誤; 嚴重性代碼說明項目文件的線路抑制狀態 錯誤CS0118「T」是一個變量,但使用像一個類型

+0

你得到了什麼錯誤,你到底想要達到什麼目的? – npinti

+0

我已經回答了在我看來最可能的問題,但會調整,如果您提供錯誤 –

+0

我剛剛添加了錯誤消息 – NewPHPer

回答

4

確保ReportTempHum和ReportVibration具有相同的接口。

List<IReportType> result; 
     if (report.ReportType == 0) { 
      result = new List<ReportTempHum>(); 
     } else if (report.ReportType == 11){ 
      result = new List<ReportVibration>(); 
     } 

     //note to verify List is not null! 
+2

如果還有很多選項,值得切換'report.ReportType'。 –

+0

是的。這是解決問題的另一種方法。但我正在通過使用「類型」尋找解決方案。謝謝。 – NewPHPer

+0

然後嘗試使用對象(或其他最接近的類),並且每次使用列表的數據時,都將其轉換爲T. –

2

這恐怕不能這樣做:

仿製藥的全部意義在於提供編譯時安全性。因此,類型對象不能用作通用參數。

有關更多信息,請參閱答案here

+1

在他的情況下'T'是一個Type對象,你不能用它作爲泛型類型參數。 – GWigWam

+1

編輯@GWigWam,歡呼 –

-1

只需使用動態的參數:

var result = new List<dynamic>(); 

更多inframtion看到:https://msdn.microsoft.com/en-us/library/dd264736.aspx

又見此相關的問題:How to create a List with a dynamic object type C#

+1

已下調。通常如果你必須使用'dynamic',你的程序設計通常是錯誤的。 '動態'不是被髮明用於常規的C#代碼。一般來說,它只能在使用COM,動態類型語言庫,ASP.NET MVC視圖等時使用,而不是像這樣。 – Bauss

0

有了這個代碼,你可以得到一個List類型T.但是,請記住它不是強類型!

Type T; 

if (report.ReportType == 0) { 
    T = typeof(ReportTempHum); 
} else if (report.ReportType == 11){ 
    T = typeof(ReportVibration); 
} 

var constructedListType = typeof(List<>).MakeGenericType(T); 
var instance = Activator.CreateInstance(constructedListType);