首页 > 解决方案 > 如何根据方法中所做的处理返回一个泛型接口?

问题描述

我需要实现的目标:编写一个从文件中读取并返回字符串列表或字符哈希集的方法。我在 .Net Core 应用程序中使用 C#,我打算以两种方式调用此方法

var stringList = ReadFileContents<string>();
var charList = ReadFileContents<char>();

我如何使用泛型实现它:

public IReadOnlyCollection<T> ReadFileContents<T>(string filePath)
{
      if (typeof(T) == typeof(string))
      {
         var downloadString = File.ReadAllLinesAsync(filePath);
         return (IReadOnlyCollection<T>)downloadString.ToList();
      }
      else
       {
          var downloadChar = File.ReadAllTextAsync(filePath);
          return (IReadOnlyCollection<T>)downloadChar.ToHashSet();
       }
}

问题:

上面的代码没有问题。我只是想获得一些意见,以检查我是否将通用返回类型用于正确的目的。

  1. 考虑到哈希集和列表是不同类型的集合,对于我的用例,使用通用返回类型是否正确?
  2. 有没有更好的方法来实现这一点而无需类型转换IReadOnlyCollection<T>或使方法看起来更干净?

标签: c#genericsreturn-typegeneric-collectionsgeneric-type-parameters

解决方案


推荐阅读