2017-10-14 92 views
0

嗨我想在運行時將對象類型傳遞到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; 
    } 
} 
+1

調用它爲什麼不自己做方法的通用? – Kroltan

回答

1

你可以讓你的函數採取通用

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 (「somestring」);並且想要在foreach循環中使用該方法,我可能想要通過,然後如何動態地執行此操作? – Asal

相關問題