【问题标题】:How I pass the type dynamically IEnumerable<T> C#我如何动态传递类型 IEnumerable<T> C#
【发布时间】:2018-03-26 17:46:18
【问题描述】:

我想在运行时将对象类型传递给IEnumerable&lt;T&gt;

例如,我必须读取 CSV 文件,它们都返回不同的数据集。

所以如果我想使用单一方法但提取一组不同的实体,我该怎么做?在下面显示的示例中,我想传递不同的实体而不是 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;
    }
}

【问题讨论】:

  • 为什么不让自己的方法通用?

标签: c# ienumerable


【解决方案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&lt;Student&gt;("somestring");调用它

【讨论】:

  • 感谢您的回答。如果我使用 GetAcgFileData("somestring");并且想在 foreach 循环中使用该方法,我可能想传递 然后 我如何动态地做到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 2015-03-19
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多