反射无法在抽象类的属性上找到私有的setter

eko*_*lis 9 .net c# reflection

当我在抽象类中拥有此属性时:

public IList<Component> Components { get; private set; }
Run Code Online (Sandbox Code Playgroud)

然后当我打电话:

p.GetSetMethod(true)
Run Code Online (Sandbox Code Playgroud)

如果p是指向我的属性的PropertyInfo对象,则为null.

但是,如果我将属性setter更改为protected,我可以通过反射看到它.为什么是这样?我似乎没有回忆起非抽象类的这个问题......

TyC*_*obb 9

我假设您在抽象类的派生类型的对象上调用它.该课程根本没有属性设定者.它只位于您的抽象基础上.这就是为什么它在你标记为时起作用的原因protected.Type获取属性设置器时,您需要使用抽象类.


Pio*_*ski 8

这是一个老线程,但我最近遇到了类似的问题,上面没有一个对我有用.添加我的解决方案,因为它可能对其他人有用.

如前所述,如果属性的setter是private,则它不存在于继承的类中.什么工作对我来说是去低一个级别使用DeclaringTypePropertyInfo

因此,使用setter检索属性的代码如下所示:

var propertyInfo = typeof(MyClass)
    .GetProperty("Components", BindingFlags.NonPublic | BindingFlags.Instance)
    .DeclaringType
    .GetProperty("Components", BindingFlags.NonPublic | BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,propertyInfo包含一个值,SetMethod以便您可以使用反射设置值.

  • 谢谢,效果很好.在我的例子中,我使用`someType.GetProperty(name).DeclaringType.GetProperty(name).GetSetMethod(true)`来检索方法.这是更短的,因为该属性是公共的,并且它只是私有的setter.我只是错过了`DeclaringType`. (2认同)