我如何通过动态类型IEnumerable C#
问题描述:
嗨我想在运行时将对象类型传递到IEnumberable<T>
。 例如 我必须读取CSV文件,它们都返回不同的数据集。 因此,如果我想使用一种方法,但提取一个不同的实体集,而不是我可以做到这一点。在下面的例子中,我想传递不同的实体而不是'学生'。我如何通过动态类型IEnumerable <T> C#
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");
+0
感谢您的回答。如果我使用GetAcgFileData
调用它为什么不自己做方法的通用? – Kroltan