我如何反映动态对象的成员? [英] How do I reflect over the members of dynamic object?

查看:9
本文介绍了我如何反映动态对象的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从在 .NET 4 中使用 dynamic 关键字声明的对象获取属性及其值的字典吗?似乎为此使用反射是行不通的.

I need to get a dictionary of properties and their values from an object declared with the dynamic keyword in .NET 4? It seems using reflection for this will not work.

示例:

dynamic s = new ExpandoObject();
s.Path = "/Home";
s.Name = "Home";

// How do I enumerate the Path and Name properties and get their values?
IDictionary<string, object> propertyValues = ???

推荐答案

如果 IDynamicMetaObjectProvider 可以提供动态成员名称,您可以获取它们.请参阅 GetMemberNames 在 apache 许可的 PCL 库中的实施 //github.com/ekonbenefits/dynamitey#dynamitey-">Dynamitey(可以在nuget中找到),它适用于ExpandoObjects和DynamicObjects实现 GetDynamicMemberNames 和任何其他 IDynamicMetaObjectProvider 提供带有 GetDynamicMemberNames 实现的元对象而没有超出 的自定义测试的是 IDynamicMetaObjectProvider.

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

在获得成员名称后,以正确的方式获得价值需要更多的工作,但 Impromptu 做到了这一点,但很难仅指出有趣的部分并使其有意义.这是文档,它等于或比反射更快,但是,不太可能比反射更快用于 expando 的字典查找,但它适用于任何对象,expando、动态或原始对象 - 您可以命名.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

这篇关于我如何反映动态对象的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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