【问题标题】:Access to ReflectedType of PropertyInfo when unboxing from Object从对象拆箱时访问 PropertyInfo 的 ReflectedType
【发布时间】:2013-03-21 16:54:31
【问题描述】:

假设我有一些通过反射过程创建的 PropertyInfo 对象。

通常我可以通过其 ReflectedType 属性获取内部对象的类型。但如果它被装箱到对象中,我就无法访问它。

var x = property.ReflectedType //Works as charm
var y = ((object)property).ReflectedType // Wouldn't work

我应该如何访问被装箱到对象的 PropertyInfo 的 ReflectedType 属性?

【问题讨论】:

  • 您真正想要完成什么?您还必须意识到您不是在“拆箱”,而是casting。一个完全不同的过程:)
  • 有这样的东西。 ((object)property) 需要知道property.ReflectedType
  • 如果您找到了问题的答案,请发布。

标签: c# reflection


【解决方案1】:

如果您确定您的 object 引用了 PropertyInfo,则转换回 PropertyInfo 并且您可以访问该属性。

var z = ((PropertyInfo)y).ReflectedType

编辑关于您对该问题的附加评论:如果您仍然可以访问您想要执行的属性变量,那么只需使用它...我觉得您对这里的某些事情感到困惑,但您应该提供更多信息,因为除非您这样做,否则没有人可以帮助您。

【讨论】:

  • private static void SetPropertyValue(object v, XElement item, PropertyInfo property) { switch (property.PropertyType.Name) { case "UInt64": property.SetValue(v, Convert.ToUInt64(item.Value), null); break; case "UInt32": property.SetValue(v, Convert.ToUInt32(item.Value), null); break; default: property.SetValue(v, item.Value, null); break; } } v 的类型为 RuntimePropertyInfo
  • @PaulKyrejto 那么您能否将此代码添加到您的问题中,并解释您实际想要做什么而不是合成代码 sn-p?您想访问此RuntimePropertyInfo 的属性吗?你只需要投射到它。
【解决方案2】:

阅读您对@fish 答案的评论时,这可能是您想要做的:

private static void SetPropertyValue(object v, XElement item, PropertyInfo property)
{
  property.SetValue(v, Convert.ChangeType(item.Value, property.PropertyType));
}

这有帮助吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2013-03-16
    • 2020-10-30
    • 2013-01-31
    • 1970-01-01
    相关资源
    最近更新 更多