我想从文件中加载值后返回一个通用列表,但是在进行类型操作后,我仍然无法使它与我一致。下面是代码;我的问题是:
- 我需要像我下面开始的那样识别每个键类型吗,还是有更快的方法?我看到“where T:...”可能与此相关,但如果可能的话,我想允许DateTime、int、string、double等类型,并且我不知道如何使用'where'来做到这些。
- 为什么我不能将DateTime项添加到datetime列表中?
- 当我尝试获取类型(listType)时,它似乎超出了范围。即使我在使用它的上一行中声明了类型,它也会说不存在这样的对象。
public static List<T> FileToGenericList<T>(string FilePath, int ignoreFirstXLines = 0, bool stripQuotes = true)
{
List<T> output = new List<T>();
Type listType = output.GetType().GetGenericArguments()[0];
try
{
using (StreamReader stream = new StreamReader(File.Open(FilePath, FileMode.Open)))
{
string line;
int currentLine = 0;
while ((line = stream.ReadLine()) != null)
{
// Skip first x lines
if (currentLine < ignoreFirstXLines) continue;
// Remove quotes if needed
if (stripQuotes == true)
{
line = line.Replace(@"""", @"");
}
// Q1 - DO I HAVE TO HAVE THIS FOR EACH TYPE OR IS THERE A QUICKER WAY
if (listType == typeof(System.DateTime))
{
DateTime val = new System.DateTime();
val = DateTime.Parse(line);
// Q2 ERROR: 'Argument type is not assignable to parameter type 'T''
output.Add(val);
// For some reason the type 'listType' from above is now out of scope when I try a cast
output.Add((listType)val);
}
if (listType == typeof(System.String))
{
//DateTime val = new System.DateTime();
//val = DateTime.Parse(line);
//output.Add(val.ToString());
}
// Continue tracking for line skipping purposes
currentLine++;
}
}
}
catch (Exception ex)
{
throw new Exception("Error - there was a problem reading the file at " + FilePath + ". Error details: " + ex.Message);
}
return output;
}