[英]Why doesn't IEnumerable of anonymous types return a List<object> on ToList()?
Here is a simplified function that I want to create: 这是我想要创建的简化函数:
static List<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList();
}
In that code block, I get the compiler error: 在该代码块中,我得到编译器错误:
Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.List' 错误CS0029无法将类型'System.Collections.Generic.List <>'隐式转换为'System.Collections.Generic.List'
In the documentation for Anonymous types, it says that anonymous types are treated as type object. 在匿名类型的文档中,它表示匿名类型被视为类型对象。 Why doesn't the C# compiler return a List<object>
on names.ToList()
? 为什么C#编译器没有在names.ToList()
上返回List<object>
?
Further more, why doesn't the following code cause an error? 此外,为什么以下代码不会导致错误? If List<<anonymous type: string FirstName>>
cannot be converted to List<object>
, then why can it be converted to IEnumberable<object>
? 如果List<<anonymous type: string FirstName>>
无法转换为List<object>
,那么为什么它可以转换为IEnumberable<object>
?
static IEnumerable<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList();
}
If
List<<anonymous type: string FirstName>>
cannot be converted toList<object>
, then why can it be converted toIEnumberable<object>
? 如果List<<anonymous type: string FirstName>>
无法转换为List<object>
,那么为什么它可以转换为IEnumberable<object>
?
That's because IEnumerable<T>
is covariant and List<T>
is not. 那是因为IEnumerable<T>
是协变的而List<T>
不是。 It has nothing to do with anonymous types. 它与匿名类型无关。
If the code you wrote was to work you'd be able to use List<string>
as List<object>
and add anything to it breaking type safety. 如果你编写的代码是工作的,你可以使用List<string>
作为List<object>
并添加任何东西来打破类型安全。
You can make your code work by passing a generic type parameter to ToList
call: 您可以通过将泛型类型参数传递给ToList
调用来使代码工作:
static List<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList<object>();
}
But there is very little you can do with that outside of this method. 但是除了这种方法之外,你几乎无法做到这一点。 You won't be able to access FirstName
property unless you use reflection. 除非使用反射,否则您将无法访问FirstName
属性。
IEnumerable<out T>
IEnumerable(T) Document IEnumerable<out T>
IEnumerable(T)Document
List<T>
List(T) Document List<T>
列表(T)文档
Note that there is "out" Generic Modifier on IEnumerable interface, which allows you put more derived type to IEnumerable. 请注意,IEnumerable接口上有“out”Generic Modifier,它允许您将更多派生类型放入IEnumerable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.