我如何动态传递类型 IEnumerable<T> C#
How I pass the type dynamically IEnumerable<T> C#
我想在运行时将对象类型传递给 IEnumerable<T>
。
例如,我必须读取 CSV 文件,它们都是 return 不同的数据集。
所以如果我想使用单一方法但提取一组不同的实体而不是我该怎么做?在下面显示的示例中,我想传递不同的实体而不是 Student
:
public List<Patient> GetAcgFileData(string fullFileName)
{
using (var sr = new StreamReader(fullFileName))
{
var reader = new CsvReader(sr);
////CSVReader will now read the whole file into an enumerable
var records = reader.GetRecords<Student>().ToList();
return records;
}
}
您可以让您的函数接受泛型
public List<T> GetAcgFileData<T>(string fullFileName) {
using (var sr = new StreamReader(fullFileName)) {
var reader = new CsvReader(sr);
////CSVReader will now read the whole file into an enumerable
var records = reader.GetRecords<T>().ToList();
return records;
}
}
然后你可以用类型GetAcgFileData<Student>("somestring");
来调用它
我想在运行时将对象类型传递给 IEnumerable<T>
。
例如,我必须读取 CSV 文件,它们都是 return 不同的数据集。
所以如果我想使用单一方法但提取一组不同的实体而不是我该怎么做?在下面显示的示例中,我想传递不同的实体而不是 Student
:
public List<Patient> GetAcgFileData(string fullFileName)
{
using (var sr = new StreamReader(fullFileName))
{
var reader = new CsvReader(sr);
////CSVReader will now read the whole file into an enumerable
var records = reader.GetRecords<Student>().ToList();
return records;
}
}
您可以让您的函数接受泛型
public List<T> GetAcgFileData<T>(string fullFileName) {
using (var sr = new StreamReader(fullFileName)) {
var reader = new CsvReader(sr);
////CSVReader will now read the whole file into an enumerable
var records = reader.GetRecords<T>().ToList();
return records;
}
}
然后你可以用类型GetAcgFileData<Student>("somestring");