为什么在c#中不能将匿名对象包装在对象列表中?

本文关键字:对象 包装 列表 不能 为什么 | 更新日期: 2023-09-27 18:06:59

为什么在c#中我们不能在对象列表中包装匿名对象?例如,我在StackOverFlow C# Linq, object definition does not contains a property

中看到过这个问题
var anynomousObject = new { Amount = 10, weight = 20 };
List<object> ListOfAnynomous = new List<object> { anynomousObject, anynomousObject };
var productQuery =
            from prod in ListOfAnynomous
            select new { prod.Amount, prod.weight };
foreach (var v in productQuery)
{
    Console.WriteLine(v.Amount);
    Console.WriteLine(v.weight);
}

,答案是他应该包装匿名列表的dynamic,但实际上我不明白为什么在运行时,我们不能得到他们的值

为什么在c#中不能将匿名对象包装在对象列表中?

匿名类型也是类型,它们被编译成实际的类。也就是说,匿名并不意味着未类型化

如果您将匿名类型实例添加到List<object>,您将它们提升到object,并且您失去了类型本身,因此,您不能访问匿名类型实例属性。

与其将它们存储在List<dynamic>中,不如采用其他解决方案:将它们存储在匿名类型的泛型列表中。因为你不能访问匿名类型名(它是匿名的,它们没有名字——好吧,它们编译成实际的类,但这是编译/运行时的内部工作方式,它是一个低级细节),你不能使用显式类型,但是c#有类型推断变量:

// compiles to string a = "hello"; assignment defines the type
var a = "hello"; 

…那么,这个呢?

// Use a type-inferred array to define the items and then convert the array
// to list!
// Now you can use each anonymous type instance properties in LINQ ;)
var listOfAnonymousInstances = new [] { new { Amount = 10, weight = 20 } }.ToList();
// If you mouse over the var keyword, you'll find that it's a List<a`>!