我有一个属于我类型的对象列表QuoteHeader
我想将此列表作为对象列表传递给能够接受List<object>
.
我的代码行是这样的...
Tools.MyMethod((List<object>)MyListOfQuoteHeaders);
但我在设计时遇到以下错误......
Cannot convert type 'System.Collections.Generic.List<MyNameSpace.QuoteHeader>'
to 'System.Collections.Generic.List<object>'
我需要对我的班级做些什么才能允许这种情况发生吗?我认为所有类都继承自对象,所以我不明白为什么这不起作用?
这不合法的原因是它不安全。假设它是合法的:
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 中这是合法的IE可枚举但不是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>
不公开任何方法takes in a T.
要解决您的问题,您可以:
- 从旧列表中创建一个新的对象列表。
- 使该方法采用 object[] 而不是
List<object>
,并使用不安全的数组协方差。
- 使该方法通用,因此需要
List<T>
- 使该方法采用 IEnumerable
- 使该方法采取
IEnumerable<object>
并使用 C# 4。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)