Vik*_*kto 1 c# linq casting anonymous-types
我想知道不允许这种转换的原因.这篇文章已经在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>);
Run Code Online (Sandbox Code Playgroud)
问题是为什么anonymous不能成功地投入IList<People>或List<People>.
anonymous实现IEnumerable<T>,而不是IList<T>肯定它不是子类型List<T>.所以它不能被强制转换为任何类型IList<T>或List<T>类型.如果这是您想要的,那么用于ToList()执行查询并将结果集存储在列表中.IEnumerable<People>?不是.这是一系列匿名类型的对象,它们复制了与a相关的一些值People.所以它是一系列匿名对象,而不是一系列人. 我还注意到,在新的C#7代码中,如果可以在应用程序中使用元组而不是匿名类型,这是更好的做法.他们在型式系统中有更好的支持,产生的收集压力更小.