简体   繁体   English

为什么C#不允许匿名转换为对象?

[英]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>

  • The value of the query expression is an object that can execute the query . 查询表达式的值是可以执行查询的对象 It is not the result set of a query execution. 它不是查询执行的结果集。 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()执行查询并将结果集存储在列表中。
  • Can the query be cast to 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM