【发布时间】:2015-08-21 02:30:58
【问题描述】:
public IList<IList<int>> FunctionName(...)
{
var list = new List<List<int>>();
...
//return list; // This doesn't compile (error listed below)
return (IList<IList<int>>)list; // Explicit cast compiles
}
当我直接返回“list”时,我得到这个错误:
> "Cannot implicitly convert type
> 'System.Collections.Generic.List<System.Collections.Generic.List<int>>'
> to
> 'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'.
> An explicit conversion exists (are you missing a cast?)"
接口返回类型不应该接受任何派生实例吗?
【问题讨论】:
-
它对我有用:/。你能告诉我们更多关于框架和语言版本的细节吗?
-
“接口返回类型不应该接受任何派生实例吗?” – 是的,但是
List<List<int>>的接口类型是IList<List<int>>。因为List<T>实现了IList<T>。它没有说明内部不同Ts 的类型转换。由covariance and contravariance 处理。 -
@Misters:您使用的是什么语言版本?我从未见过允许这样做的 c# 编译器。
-
尝试同时针对 .NET 4.5 和 .NET 4.0,同样的错误:/
标签: c# interface covariance