【问题标题】:Getting a PropertyInfo of a dynamic object获取动态对象的 PropertyInfo
【发布时间】:2016-10-29 17:22:28
【问题描述】:

我有一个库,它依赖于它接收到的类的 PropertyInfo(获取和设置值)进行大量反射工作。

现在我希望能够使用动态对象,但我找不到如何获取动态属性的 PropertyInfo。我已经检查了替代方案,但对于那些我需要在使用 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);

是否有可能以某种方式获取或创建 PropertyInfo 以便能够在动态对象上使用它的 GetValue()SetValue()

【问题讨论】:

  • 我无法重现这个。您确定属性MyID 存在于实体上并且是公开的吗?
  • @DavidL 对不起,我会发布一个更好的例子。它是动态的,因此该属性仅在已设置且公开的情况下才会存在。
  • 请注意,它可能不是实际属性。一些类型,如ExpandoObject,通过将运行时绑定重定向到名称/值字典来模拟属性。
  • 我也无法重现它,GetProperties() is 为我的dynamic 变量返回一个充满PropertyInfo 的数组。
  • 看看thisthis能不能帮到你

标签: c# dynamic reflection


【解决方案1】:

ExpandoObject 实际上只是一本字典。只需投射即可获取字典。

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");
}

您可以修改 Mapping 方法以检查传入的对象是否是动态的,并通过仅遍历字典键的不同路径进行路由。

https://dotnetfiddle.net/VQQZdy

【讨论】:

  • 我试图避免字典转换,因为我必须更改代码中假定PropertyInfo 的每个地方,现在几乎无处不在......
猜你喜欢
  • 2013-03-16
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 2015-03-07
  • 2011-12-27
相关资源
最近更新 更多