IList 存儲匿名類型對象(new {a=1,b=2,c=3,d=4}),需遍歷每行每列值。因匿名類型編譯器生成內部類,只能通過反射動態獲取屬性。
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
var list = new List<object> {
new { a=1, b=2, c=3, d=4 },
new { a=11, b=12, c=13, d=14 },
new { a=21, b=22, c=23, d=24 }
};
foreach (var obj in list) {
var props = obj.GetType().GetProperties();
foreach (var prop in props) {
Console.Write(prop.GetValue(obj) + "\t");
}
Console.WriteLine();
}
}
}
1 2 3 4
11 12 13 14
21 22 23 24
List<MyDto> 避免反射開銷,代碼更清晰。PropertyInfo[] 或使用 FastMember/Expression Tree 提速。System.Text.Json 序列化為 JsonElement 再遍歷,無需反射。