返回列表中的具体实现
我知道这不能编译,但为什么不应该编译呢?
public interface IReportService {
IList<IReport> GetAvailableReports();
IReport GetReport(int id);
}
public class ReportService : IReportService {
IList<IReport> GetAvailableReports() {
return new List<ConcreteReport>(); // This doesnt work
}
IReport GetReport(int id){
return new ConcreteReport(); // But this works
}
}
I know this doesnt compile but why shouldnt it?
public interface IReportService {
IList<IReport> GetAvailableReports();
IReport GetReport(int id);
}
public class ReportService : IReportService {
IList<IReport> GetAvailableReports() {
return new List<ConcreteReport>(); // This doesnt work
}
IReport GetReport(int id){
return new ConcreteReport(); // But this works
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为协方差。您可以让它在 .NET 4 中工作(阅读链接)。
It's because of covariance. You can get it to work in .NET 4 (read the link).
尝试更改为这个
Try change to this
我最近自己也遇到了这个问题,发现使用 IEnumerable 而不是 List 可以解决问题。这是一个相当令人沮丧的问题,但是一旦我找到了问题的根源,它就有意义了。
这是我用来找到解决方案的测试代码:
I recently ran into this problem myself, and found that using IEnumerable instead of List solves the problem. It was quite a frustrating issue, but once I found the source of the problem, it made sense.
Here's the test code I used to find the solution: