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

查看:217
本文介绍了如何访问匿名类型的属性在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的:

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

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

...我想知道如果我可以再抓匿名对象的选中属性。我不知道这甚至有可能。试着这样做:

... 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:

如果(nodes.Any(N =&GT; N [选中] == 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天全站免登陆