我怎么反映过来动态对象的成员?对象、成员、我怎么、动态

2023-09-08 08:52:02 作者:爱笑的萌汉纸

我需要从与.NET 4的动态关键字声明的对象获取属性及其值的字典?看来使用反射否则将无法正常工作。

例如:

 动态S =新ExpandoObject();
s.Path =/家;
s.Name =家;

//我如何枚举的路径和名称的属性,并得到他们的价值观?
IDictionary的<字符串,对象> propertyValues​​ = ???
 

解决方案

如果该IDynamicMetaObjectProvider能提供动态成员的名字,你可以让他们。请参阅 GetMemberNames 在Apache许可实施PCL库 Dynamitey (它可以在的NuGet可以找到),它适用于 ExpandoObject DynamicObject 实现小号 GetDynamicMemberNames 和其他 IDynamicMetaObjectProvider 谁提供了一个元对象与 GetDynamicMemberNames 无需定制的实现测试超出是IDynamicMetaObjectProvider

获取成员名称是多一点的工作来获取值的正确方法,但即兴做到这一点,但它很难指向仅仅是有趣的位,并让它意义之后。这里的文档,它是等于或大于反射快,但是,不太可能比对的expando字典查找更快,但它可以用于任何目的,Expando的,动态的或原创 - 你的名字

国旗做微信头像违法 发完朋友圈网友慌了 到底怎么回事

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.

Example:

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 = ???

解决方案

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.

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.

 
精彩推荐
图片推荐