简体   繁体   English

获取动态对象的PropertyInfo

[英]Getting a PropertyInfo of a dynamic object

I have a library that is doing a bunch of reflection work relying on the PropertyInfo of the classes it receives (to get and set values). 我有一个库,它依赖于它接收的类的PropertyInfo(获取和设置值)进行一堆反射工作。

Now I want to be able to work with dynamic objects, but I can't find how to get the PropertyInfo of a dynamic's properties. 现在我希望能够使用动态对象,但我找不到如何获取动态属性的PropertyInfo。 I've checked the alternatives, but for those I'd need to change everywhere I use PropertyInfo to get/set values. 我已经检查了替代方案,但对于那些我需要改变的地方,我使用PropertyInfo来获取/设置值。

dynamic entity = new ExpandoObject();
entity.MyID = 1;

// - Always null
PropertyInfo p = entity.GetType().GetProperty("MyID");
// - Always null
PropertyInfo[] ps = entity.GetType().GetProperties();

// - These are called everywhere in the code
object value = p.GetValue(entity);
p.SetValue(entity, value);

Is it possible to get or create a PropertyInfo somehow just to be able to use it's GetValue() and SetValue() on a dynamic object? 有可能以某种方式获取或创建PropertyInfo只是为了能够在动态对象上使用它的GetValue()SetValue()吗?

Under the covers an ExpandoObject is really just a dictionary. 在封面下, ExpandoObject实际上只是一本字典。 You can get at the dictionary just by casting it. 您可以通过投射来获取字典。

dynamic entity = new ExpandoObject();
entity.MyID = 1;

if(entity.GetType() == typeof(ExpandoObject))
{
    Console.WriteLine("I'm dynamic, use the dictionary");
    var dictionary = (IDictionary<string, object>)entity;
}
else
{
    Console.WriteLine("Not dynamic, use reflection");
}

You could modify your Mapping method to check if the object being passed in is dynamic and route through a different path that just iterates over the keys of the dictionary. 您可以修改Mapping方法以检查传入的对象是否是动态的,并通过不同的路径路由,该路径只是迭代字典的键。

https://dotnetfiddle.net/VQQZdy https://dotnetfiddle.net/VQQZdy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM