为什么GetProperty()找不到最派生类型的属性,但会发现它是类型实现的接口之一?

时间:2014-02-14 15:11:19

标签: c# .net reflection

我有一些非常复杂的对象传递给我的回调,我不控制对象设计,也不知道在那里会发生什么。我所知道的是,它可能实现了SpecificInterface接口,该接口具有SpecificProperty公共属性的公共getter。

我有这段代码:

dynamic theObjectPassed = ...;
Type objectType = theObjectPassed.GetType();
var objectProperty = objectType.GetProperty("SpecificProperty");
Type interfaceType = objectType.GetInterface("SpecificInterface");
var interfaceProperty = interfaceType.GetProperty("SpecificProperty");

以某种方式objectProperty变为null,但interfaceProperty变为非空。

为什么在接口中找到属性,而不是从该接口派生的类中找到属性?

1 个答案:

答案 0 :(得分:3)

创建复杂对象的类必须通过显式接口实现扩展接口SpecificInterface;因此,除非通过显式接口访问类的对象,否则其属性不可访问。见this