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>
。它并没有说明不同T
的类型转换。这由协变和逆变处理。 - poke