2017-01-16 91 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);