如何在 C# 中访问匿名类型的属性?

问题描述:

我有这个:

List<object> nodes = new List<object>(); 

nodes.Add(
new {
    Checked     = false,
    depth       = 1,
    id          = "div_" + d.Id
});

...我想知道我是否可以获取匿名对象的Checked"属性.我不确定这是否可能.尝试这样做:

... and I'm wondering if I can then grab the "Checked" property of the anonymous object. I'm not sure if this is even possible. Tried doing this:

if (nodes.Any(n => n["Checked"] == false)) ...但它不起作用.

if (nodes.Any(n => n["Checked"] == false)) ... but it doesn't work.

谢谢

如果您想要一个匿名类型的强类型列表,您还需要将该列表设为匿名类型.最简单的方法是将序列(例如数组)投影到列表中,例如

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

然后您就可以像这样访问它:

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

由于编译器的工作方式,一旦您创建了列表,以下内容也应该可以工作,因为匿名类型具有相同的结构,因此它们也是相同的类型.不过,我没有编译器来验证这一点.

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });