我想知道不允许这种类型转换的原因。此主题已在 post in SO 中讨论过,但我想要低级解释为什么这在本地是不可能的。
为什么这些转换会失败?
OBS:我知道可以通过反射(reflection)来做到这一点。
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 代码中,如果可以的话,最好在应用程序中使用元组而不是匿名类型。它们在类型系统中有更好的支持,产生的回收压力更小。
关于c# - 为什么 C# 不允许匿名转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833520/