为什么我不能从 List<MyClass> 投射列出<对象>? [英] Why can't I cast from a List<MyClass> to List<object>?
问题描述
我有一个对象列表,属于我的类型 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:
- 从旧列表中创建一个新的对象列表.
- 使该方法采用 object[] 而不是
List
,并使用不安全的数组协方差. - 使方法通用,因此它需要一个
List
- 使方法采用 IEnumerable
- 使方法采用
IEnumerable
并使用 C# 4.
- Create a new list of objects out of the old list.
- Make the method take an object[] rather than a
List<object>
, and use unsafe array covariance. - Make the method generic, so it takes a
List<T>
- Make the method take IEnumerable
- Make the method take
IEnumerable<object>
and use C# 4.
这篇关于为什么我不能从 List<MyClass> 投射列出<对象>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!