小编bre*_*zeZ的帖子

为什么我不能为C#中具有IList <IList <int >>返回类型的函数返回List <List <int >>类型的变量

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
}
Run Code Online (Sandbox Code Playgroud)

当我直接返回"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?)"
Run Code Online (Sandbox Code Playgroud)

接口返回类型不应该接受任何派生实例吗?

c# interface covariance

3
推荐指数
1
解决办法
306
查看次数

标签 统计

c# ×1

covariance ×1

interface ×1