如何在 C# 中访问匿名类型的属性? [英] How to access property of anonymous type in C#?

查看:51
本文介绍了如何在 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 */ });

这篇关于如何在 C# 中访问匿名类型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆