[英]Why does C# not allow anonymous cast to objects?
I would like to know the reason that does not allow this type of convertion. 我想知道不允许这种转换的原因。 The subject was already approached in this post in SO , but I want the low level explanation on why this is not possible natively.
SO的这篇文章中已经谈到了这个主题,但是我想对为什么这在本机上不可能做一个低级的解释。
Why does these casts fail? 为什么这些强制转换失败?
OBS: I know it is possible to do so by reflection. OBS:我知道可以通过反思来做到这一点。
IList<People> peopleList = new List<People>()
{
new People() { Name = "Again", Age = 10 },
new People() { Name = "Over", Age = 20 },
new People() { Name = "Jonh", Age = 30 },
new People() { Name = "Enzo", Age = 40 },
};
var anonymous = (from p in peopleList
select new
{
Name = p.Name,
Age = p.Age
});
// Does not work
IList<People> listt = (IList<People>)anonymous;
//Does not Work
IList<People> listt = (anonymous as List<People>);
The question is why anonymous
cannot be successfully cast to IList<People>
or List<People>
. 问题是为什么不能将
anonymous
成功转换为IList<People>
或List<People>
。
anonymous
implements IEnumerable<T>
, not IList<T>
and certainly it does not subtype List<T>
. anonymous
实现IEnumerable<T>
,而不是IList<T>
并且肯定不是子类List<T>
。 So it cannot be cast to any IList<T>
or List<T>
type. IList<T>
为任何IList<T>
或List<T>
类型。 If that's what you want then use ToList()
to execute the query and store the result set in a list. ToList()
执行查询并将结果集存储在列表中。 IEnumerable<People>
? IEnumerable<People>
吗? No. It is a sequence of anonymously-typed objects that have copied some of the values associated with a People
. People
相关联的某些值。 So it is a sequence of anonymous objects, not a sequence of people. I note also that in new C# 7 code it's a better practice to use tuples instead of anonymous types if you can in your application. 我还注意到,在新的C#7代码中,如果可以在应用程序中使用元组而不是匿名类型,则是更好的做法。 They have better support in the type system and produce less collection pressure.
它们在类型系统中具有更好的支持,并产生较小的收集压力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.