gpt4 book ai didi

c# - 为什么匿名类型的 IEnumerable 不在 ToList() 上返回 List
转载 作者:太空狗 更新时间:2023-10-29 22:35:46 24 4
gpt4 key购买 nike

这是我想创建的一个简化函数:

static List<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList();
}

在那个代码块中,我得到了编译器错误:

Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.List'

documentation对于匿名类型,它表示匿名类型被视为类型对象。为什么 C# 编译器不返回 List<object>names.ToList()

更进一步,为什么下面的代码不会报错呢?如果List<<anonymous type: string FirstName>>无法转换为 List<object> , 那为什么可以转换成IEnumerable<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 to List<object>, then why can it be converted to IEnumerable<object>?

那是因为IEnumerable<T>是协变的并且List<T>不是。它与匿名类型无关。

如果您编写的代码能够正常工作,您就可以使用 List<string>作为List<object>并向其中添加任何破坏类型安全的内容。

您可以通过将通用类型参数传递给 ToList 来使您的代码正常工作调用:

static List<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList<object>();
}

但除此方法外,您几乎无能为力。您将无法访问 FirstName属性,除非你使用反射。

关于c# - 为什么匿名类型的 IEnumerable 不在 ToList() 上返回 List<object>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48812449/

24 4 0