繁体   English   中英

在继承中获取属性的私有setter

[英]get a property's private setter within inheritance

以下是我的代码:

class Foo
{
    public string Bar { get; private set; }
}

var prop = typeof(Foo).GetProperty("Bar");
if (prop != null)
{
    // The property exists
    var setter = prop.GetSetMethod(true);
    if (setter != null)
    {
        // There's a setter
        Console.WriteLine(setter.IsPublic);
    }
}

是的,你可以想象,这完全正确。 但是当有了遗产时,事情就会有所不同:

class Foo
{
    public string Bar { get; private set; }
}

class A : Foo
{ 

}

当然我改变了这一行:

var prop = typeof(Foo).GetProperty("Bar");

var prop = typeof(A).GetProperty("Bar");

然后,setter变为null,并且控制台什么都不打印!

所以为什么?

顺便说一句,是否有一些解决方法可以实现这一目标或完全采用另一种方式?

任何帮助,将不胜感激。 谢谢。

一般的解决方案是打电话

var prop = GetType().GetProperty("Bar").DeclaringType.GetProperty("Bar");

我同意,这不是很直观。

所以为什么?

A而言, Bar是只读的 - 你不能从A调用setter,所以当你要求A的属性时,没有setter是有意义A

另一种方法是使用绑定标志只询问声明的属性 - 然后沿着继承链向上走,直到找到实际的属性声明。 你必须这样做有点奇怪,但它确实有一定的意义,因为属性确实不同的,这取决于你是否从声明类的上下文来到它。

我对这种行为感到惊讶 - 但并不震惊

您可以通过在属性信息中使用SetValue方法来设置具有反射的私有属性,即使您无法获取set方法也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM