1

在这种情况下,我有两种类型 - A 类型和 B 类型。A 类型存在于更高层中,而不是我在下面实现代码的地方,它具有 B 类型的属性。B 类型在层中定义我正在工作的(下层,认为平台)。我正在尝试访问类型 B 的类型 A 的属性。如果我理解正确,通过反射我应该能够反射类型 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.'

我在这里误解了什么吗?

4

1 回答 1

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);
于 2018-07-19T00:07:28.957 回答