【问题标题】:Unable to extract a property value using reflection无法使用反射提取属性值
【发布时间】:2018-07-19 00:02:28
【问题描述】:

在这种情况下,我有两种类型 - A 类型和 B 类型。A 类型存在于更高层中,而不是我在下面实现代码的地方,它具有 B 类型的属性。B 类型已定义在我正在工作的层(下层,认为平台)中。我正在尝试访问类型 A 的 B 类型属性。如果我理解正确,通过反射我应该能够反映类型 A 并获得这个对象(B类)如下

Type targetTypeA = instanceOfTypeA.GetType();
PropertyInfo someProperty = instanceOfTypeA.GetProperty("PropertyName"); // again just to clarify, the type of this property is 'B' and present in this layer that I'm working in.
object propertyValue = someProperty.GetValue(targetTypeA, null);

GetValue() 方法抛出以下异常:System.Reflection.TargetException: 'Object does not match target type.'

我在这里误解了什么吗?

【问题讨论】:

  • 想通了,我必须传入 'instanceOfTypeA' 而不是 targetTypeA

标签: c# reflection propertyinfo getvalue


【解决方案1】:

我传递的是“类型”而不是实际实例。以下代码有效:

Type targetTypeA = instanceOfTypeA.GetType();
PropertyInfo someProperty = instanceOfTypeA.GetProperty("PropertyName"); // again just to clarify, the type of this property is 'B' and present in this layer that I'm working in.
object propertyValue = someProperty.GetValue(instanceOfTypeA, null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多