簡體   English   中英

我如何動態傳遞類型IEnumerable <T> C#

[英]How I pass the type dynamically IEnumerable<T> C#

嗨,我想在運行時將對象類型傳遞給IEnumberable<T> 例如,我必須讀取CSV文件,並且它們都返回不同的數據集。 因此,如果我想使用一種方法,但提取的實體集與我可以做到的方式不同。 在下面的示例中,我想傳遞不同的實體,而不是“學生”。

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");類型來調用它GetAcgFileData<Student>("somestring");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM