gpt4 book ai didi

c# - 为什么我不能从 List 转换为 List
转载 作者:IT王子 更新时间:2023-10-29 04:26:21 27 4
gpt4 key购买 nike

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

我的代码行是...

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

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

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

我需要对我的类(class)做些什么才能允许这样做吗?我认为所有类都继承自对象,所以我不明白为什么这行不通?

最佳答案

这不合法的原因是它不安全。假设它是合法的:

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

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

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

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

在 C# 4 中,这在 IEnumerable 上是合法的,但在 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>不公开任何接受 T 的方法。

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

  • 从旧列表中创建一个新的对象列表。
  • 使方法采用对象[] 而不是List<object> ,并使用不安全的数组协方差。
  • 使方法通用,所以它需要一个 List<T>
  • 使方法采用 IEnumerable
  • 使方法采用IEnumerable<object>并使用 C# 4。

关于c# - 为什么我不能从 List<MyClass> 转换为 List<object>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5881677/

27 4 0