相关疑难解决方法(0)

C#方差问题:将List <Derived>分配为List <Base>

请看以下示例(部分取自MSDN博客):

class Animal { }
class Giraffe : Animal { }

static void Main(string[] args)
{
    // Array assignment works, but...
    Animal[] animals = new Giraffe[10]; 

    // implicit...
    List<Animal> animalsList = new List<Giraffe>();

    // ...and explicit casting fails
    List<Animal> animalsList2 = (List<Animal>) new List<Giraffe>();
}
Run Code Online (Sandbox Code Playgroud)

这是一个协方差问题吗?这将在未来的C#版本中得到支持吗?是否有任何聪明的解决方法(仅使用.NET 2.0)?

c# covariance

54
推荐指数
4
解决办法
2万
查看次数

协方差和IList

我想要一个Covariant集合,其项目可以通过索引检索.IEnumerable是我所知道的唯一.net集合,它是Covariant,但它没有这个索引支持.

具体来说,我想这样做:

List<Dog> dogs = new List<Dog>();

IEnumerable<Animal> animals = dogs;
IList<Animal> animalList = dogs; // This line does not compile
Run Code Online (Sandbox Code Playgroud)

现在,我知道为什么这是一个问题.List实现ICollection具有Add方法.通过向上投射IList动物,它将允许后续代码添加"真实" List<Dog>集合中不允许的任何类型的动物.

那么有人知道一个支持索引查找的集合也是协变的吗?我想不创造自己的.

.net c# .net-4.0 covariance

47
推荐指数
3
解决办法
7466
查看次数

c#中的协方差

是否有可能投下List<Subclass>List<Superclass>在C#4.0?

这些方面的东西:

class joe : human {}

List<joe> joes = GetJoes();

List<human> humanJoes = joes;
Run Code Online (Sandbox Code Playgroud)

这不是协方差的意思吗?

如果你能做到:

human h = joe1 as human;
Run Code Online (Sandbox Code Playgroud)

你为什么不能这样做

List<human> humans = joes as List<human>; 
Run Code Online (Sandbox Code Playgroud)

因为那个项目已经被贬低了,所以做人类[0]是不合法的,每个人都会很高兴.现在唯一的选择是创建一个新的List

c# casting covariance

19
推荐指数
2
解决办法
2141
查看次数

将对象列表转换为List vs IList

刚发现这个:

Func<List<object>> foo = () => new List<object>();
List<string> s = (List<string>)foo();
IList<string> s1 = (IList<string>)foo();
Run Code Online (Sandbox Code Playgroud)

编译器抱怨转换为List(有意义),但没有提及IList.让我想知道为什么会这样?

c# casting

10
推荐指数
1
解决办法
2254
查看次数

标签 统计

c# ×4

covariance ×3

casting ×2

.net ×1

.net-4.0 ×1