C# 为什么可以';ti返回一个List类型的变量<;列表<;int>&燃气轮机;对于具有IList的函数<;IList<;int>&燃气轮机;C中的返回类型# public IList函数名(…) { var list=新列表(); ... //return list;//这不可编译(下面列出的错误) 返回(IList)列表;//编译显式强制转换 }
当我直接返回“list”时,我得到以下错误:C# 为什么可以';ti返回一个List类型的变量<;列表<;int>&燃气轮机;对于具有IList的函数<;IList<;int>&燃气轮机;C中的返回类型# public IList函数名(…) { var list=新列表(); ... //return list;//这不可编译(下面列出的错误) 返回(IList)列表;//编译显式强制转换 },c#,interface,covariance,C#,Interface,Covariance,当我直接返回“list”时,我得到以下错误: public IList<IList<int>> FunctionName(...) { var list = new List<List<int>>(); ... //return list; // This doesn't compile (error listed below) return (IList<IList&
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
}
>“无法隐式转换类型
>'System.Collections.Generic.List'
>到
>'System.Collections.Generic.IList'。
>存在显式转换(是否缺少转换?)
接口返回类型不应该接受任何派生实例吗?有一个微妙的类型错误。如果这样做有效,您可能会出现此类错误
> "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=新列表();
IList IList=list;//想象一下,在这个世界上,这是合法的
//类型系统已允许此操作
添加(新的int[]{1,2,3});
//这实际上是一个数组!不是名单
列表优先=列表[0];
您可以使用IReadOnlyList
来满足您的需求。由于它是只读的,所以该类型错误无法在代码中显示。但您永远不能在外部列表中添加元素或更新值。通用接口的这一特性称为“协方差”
IReadOnlyList-ilist=list;
它对我有效:/。你能给我们更多关于框架和语言版本的细节吗?“接口返回类型不应该接受任何派生实例吗?”–是的,但是List
的接口类型是IList
。因为List
实现了IList
。它没有说明内部不同T
s的类型转换。先生:你用的是什么语言版本?我从未见过一个c#编译器会允许这样做。尝试同时针对.NET 4.5和.NET 4.0,同样的错误:/谢谢。但是,函数签名指示我需要返回IList,而在函数内部,我确实需要向列表中添加项来构造它(因此我不能将其设置为只读)。有什么办法吗?@Breeze:如果你愿意列一个新的清单,有很多方法可以做到。首先,您可以在finalilist
上调用.ToList()
,然后得到您想要的。
List<List<int>> list = new List<List<int>>();
IList<IList<int>> ilist = list; // imagine a world where this was legal
// This is already allowed by the type system
ilist.Add(new int[] { 1, 2, 3 });
// This is actually an array! Not a List<>
List<int> first = list[0];
IReadOnlyList<IList<int>> ilist = list;