为什么我不能从 List<MyClass> 投射列出<对象>? [英] Why can&#39;t I cast from a List&lt;MyClass&gt; to List&lt;object&gt;?

查看:34
本文介绍了为什么我不能从 List<MyClass> 投射列出<对象>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,属于我的类型 QuoteHeader,我想将此列表作为对象列表传递给能够接受 List 的方法;.

I have a List of objects, which are of my type QuoteHeader and I want to pass this list as a list of objects to a method which is able to accept a List<object>.

我的代码行读取...

Tools.MyMethod((List<object>)MyListOfQuoteHeaders);

但我在设计时收到以下错误...

But I get the following error at design time...

Cannot convert type 'System.Collections.Generic.List<MyNameSpace.QuoteHeader>' 
to 'System.Collections.Generic.List<object>'

我需要对我的班级做什么才能允许这样做吗?我认为所有类都继承自 object 所以我不明白为什么这不起作用?

Do I need to do anything to my class to allow this? I thought that all classes inherit from object so I can't understand why this wouldn't work?

推荐答案

之所以不合法,是因为它不安全.假设它是合法的:

The reason this is not legal is because it is not safe. Suppose it were legal:

List<Giraffe> giraffes = new List<Giraffe>();
List<Animal> animals = giraffes; // this is not legal; suppose it were.
animals.Add(new Tiger());  // it is always legal to put a tiger in a list of animals

但动物"实际上是长颈鹿的列表;你不能把老虎列入长颈鹿名单.

But "animals" is actually a list of giraffes; you can't put a tiger in a list of giraffes.

不幸的是,在 C# 中,这对于引用类型的数组是合法的:

In C# this is, unfortunately, legal with arrays of reference type:

Giraffe[] giraffes = new Giraffe[10];
Animal[] animals = giraffes; // legal! But dangerous because...
animals[0] = new Tiger(); // ...this fails at runtime!

在 C# 4 中,这在 IEnumerable 上是合法的,但在 IList 上不合法:

In C# 4 this is legal on IEnumerable but not IList:

List<Giraffe> giraffes = new List<Giraffe>();
IEnumerable<Animal> animals = giraffes; // Legal in C# 4
foreach(Animal animal in animals) { } // Every giraffe is an animal, so this is safe

它是安全的,因为 IEnumerable 不暴露任何接受 T 的方法.

It is safe because IEnumerable<T> does not expose any method that takes in a T.

要解决您的问题,您可以:

To solve your problem you can: