c# - 如何根据方法中所做的处理返回一个泛型接口?
问题描述
我需要实现的目标:编写一个从文件中读取并返回字符串列表或字符哈希集的方法。我在 .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();
}
}
问题:
上面的代码没有问题。我只是想获得一些意见,以检查我是否将通用返回类型用于正确的目的。
- 考虑到哈希集和列表是不同类型的集合,对于我的用例,使用通用返回类型是否正确?
- 有没有更好的方法来实现这一点而无需类型转换
IReadOnlyCollection<T>
或使方法看起来更干净?
解决方案
推荐阅读
- vb.net - 多选或多选不能全选
- awk - 如果使用 AWK 未找到匹配项,则运行命令
- ionic-framework - Scrolling ion-content is scrolling header and tabs wrongly
- python - 在线程中重定向烧瓶请求
- python - 如何阻止 pydoc 在 f 字符串上出错?
- c++ - 为什么我们需要在引用右值函数参数上显式调用 std::move ?
- lattice-diamond - Linux 上的 Lattice Diamond v 3.11:ftdio_sio 的问题
- android - Android Q 保存的 Uris 在新手机上是否有效?
- angular - Angular 7 - 自定义烤面包机不显示消息
- javascript - 不能让我的方法连接 2 个值