【发布时间】:2018-03-08 05:34:49
【问题描述】:
问题:我有许多要解析的文件类型。每个解析一个文件并返回一个对象的结果(List<>)。我只想拥有一个IFileParser 接口,并在调用Parse 时指定解析器类型和返回集
我有这样的界面
public interface IFileParser
{
TResponse Parse<TFileParserType,TResponse>(string file);
}
被注入到这样的服务中
private readonly IFileParser _fileParser;
public CarService(IFileParser fileParser)
{
_fileParser = fileParser;
}
被使用
var cardatas = _fileParser.Parse<CarFileParser, List<CarData>>("car.txt");
var bikedatas = _fileParser.Parse<BikeFileParser, List<BikeData>>("bike.txt");
实现 - 这部分不起作用...为什么? 返回的错误是
无法将类型“System.Collections.Generic.List
”隐式转换为“System.Collections.Generic.List ”
public class CarFileParser : IFileParser
{
public List<CarData> Parse(string filePath)
{
return new List<CarData>() //does not work...why??
}
public TResponse Parse<TType, TResponse>(string file)
{
throw new NotImplementedException();
//this is what it should be
//but how do I return a List<CarData>
}
}
【问题讨论】:
-
问题是什么?代码中TType有什么用?
-
@ChetanRanpariya 是“文件解析器类型”
-
CarData与ClearingHouseSuperannuationData有什么关系?为什么你尝试返回return new List<CarData>()是返回类型被指定为List<ClearingHouseSuperannuationData>? -
你能为 CarData 和 ClearingHouseSuperannuationData 添加代码吗...这些类型兼容吗?
-
好像是数组逆变问题...