【发布时间】: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