分配类型 .net
Assigning a type .net
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 条件将类型分配到列表中。但是有些错误。
我该怎么做?
提前致谢!
编辑:错误;
严重性代码描述项目文件行抑制状态
错误 CS0118 'T' 是一个变量,但像类型一样使用
恐怕做不到:
泛型的全部意义在于提供 compile-time 安全性。因此,类型对象不能用作泛型参数。
请参阅答案 here 了解更多信息。
确保 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!
只需使用 dynamic 作为参数:
var result = new List<dynamic>();
有关更多信息,请参阅:https://msdn.microsoft.com/en-us/library/dd264736.aspx
另请参阅此相关问题:How to create a List with a dynamic object type C#
使用此代码,您可以获得类型 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);
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 条件将类型分配到列表中。但是有些错误。
我该怎么做?
提前致谢!
编辑:错误; 严重性代码描述项目文件行抑制状态 错误 CS0118 'T' 是一个变量,但像类型一样使用
恐怕做不到:
泛型的全部意义在于提供 compile-time 安全性。因此,类型对象不能用作泛型参数。
请参阅答案 here 了解更多信息。
确保 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!
只需使用 dynamic 作为参数:
var result = new List<dynamic>();
有关更多信息,请参阅:https://msdn.microsoft.com/en-us/library/dd264736.aspx
另请参阅此相关问题:How to create a List with a dynamic object type C#
使用此代码,您可以获得类型 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);