English 中文(简体)
为什么我把名单<int>寄至可观<object>,载于:NET4.0。
原标题:Why can t I assign List<int> to IEnumerable<object> in .NET 4.0

我试图这样做:

IEnumerable<object> ids = new List<string>() { "0001", "0002", "0003" };

它发挥了巨大作用。

But when 我试图这样做:

IEnumerable<object> intIds = new List<System.Int32>() { 1, 2, 3 };

Visual Studio tells me: Cannot implicitly convert type System.Collections.Generic.List to System.Collections.Generic.IEnumerable . An explicit conversion exists (are you missing a cast?)

为什么如此?

问题回答

简言之,对价值类型的类型论据而言,4网中的一般差异不支持。

它可以为参考类型工作的原因是,一旦《刑法》决定它知道通用转换是安全的,它就能够以同样的方式对待所有参考价值——在内部都有同样的代表。 第actual换算为string reference into an object reference, or反之亦然,如果你明确知道该词的提及——该词基本上具有相同的范围。 因此,产生的本地法典只能把参考文献作为参考文献处理,并高兴地看到,围绕差异的规则保证在类型安全层面不会发生任何新情况,而且不会对价值本身进行任何转换。

sn t关于价值类型,or,关于换算为“参考换算”(即代表制-保值)。 因此,你可以通过以下方式撰写:IE amountable<XName> name = new list<string>

From MSDN Blogs > C# Frequently Asked Questions > Covariance and Contravariance FAQ:

Variance is supported only if a type parameter is a reference type. Variance is not supported for value types. The following doesn’t compile either:

// int is a value type, so the code doesn t compile.
IEnumerable<Object> objects = new List<int>(); // Compiler error here.

另一种解决办法是使用可观的推广方法。 种姓:

Dim a as IEnumerable(Of Integer) = GetA()

MethodThatTakesIEnumerableOfObject(a.Cast(Of Object))




相关问题
XmlSerializer doesn t serialize everything in my class

I have a very basic class that is a list of sub-classes, plus some summary data. [Serializable] public class ProductCollection : List<Product> { public bool flag { get; set; } public ...

System.Linq and IEnumerable Group Help

I m just getting my feet wet with Linq and IEnumerable, and I m needing help in trying to determine if my objects contain matches for a card game. I think if I get the first one figured out, the other ...

What is the benefit to using List<T> over IEnumerable<T>?

or the other way around? I use generic lists all the time. But I hear occasionally about IEnumerables, too, and I honestly have no clue (today) what they are for and why I should use them. So, at ...

热门标签