将值类型的“列表”传递给需要引用类型的“IEnumerable”的方法

Passing `List` of value types to a method expecting `IEnumerable` of reference types

我想知道为什么在 .NET 中无法将值类型列表传递给需要 IEnumerable 引用类型的方法。例如,

void MyMethod(IEnumerable<object> items) {}
...
var dtList = new List<DateTime> { DateTime.Now };
MyMethod(dtList); // not possible, but it's possible to make a cast object o = DateTime.Now;

由于这对引用类型很好用,我得出的结论是,对于值类型,集合中的 每个元素 都需要装箱,它可能会碰到性能,但我可能是错的,还有一些其他的事情需要考虑。

因为值类型不是协变的(它们需要装箱),因此失去了它们的身份 - compiler 被指示按规范保存。但是你可以.Cast<object>()(以拳击为代价),这对你来说可能是也可能不是问题。

有关 identity 的更多详细信息,您可以在 Representation and identity

上查看 Eric Lipperts 的博客

All the built-in reference conversions are identity-preserving. This is why covariant and contravariant conversions of interface and delegate types require that all varying type arguments be of reference types. To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving.