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

Why does C# not allow anonymous cast to objects?

我想知道不允许这种类型转换的原因。这个主题已经在 post in SO 中讨论过,但我想要低级解释为什么这在本地是不可能的。

为什么这些转换会失败?

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>);

问题是为什么anonymous不能成功转换为IList<People>List<People>

  • 查询表达式的值为一个可以执行查询的对象。它不是查询执行的结果集。 anonymous 实现了 IEnumerable<T>,而不是 IList<T>,当然它也没有子类型 List<T>。所以它不能转换为任何 IList<T>List<T> 类型。如果这是您想要的,那么使用 ToList() 执行查询并将结果集存储在列表中。
  • 可以将查询转换为 IEnumerable<People> 吗?不。它是一系列匿名类型的对象,它们复制了一些与 People 关联的值。所以它是一系列匿名对象,而不是一系列人。

我还注意到,在新的 C# 7 代码中,如果可以的话,最好在应用程序中使用元组而不是匿名类型。它们对类型系统有更好的支持,产生的收集压力更小。