【问题标题】:get a property's private setter within inheritance在继承中获取属性的私有设置器
【发布时间】:2013-06-25 19:51:06
【问题描述】:

以下是我的代码:

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,控制台不打印任何内容!

所以...为什么?

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

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

【问题讨论】:

    标签: c# inheritance reflection properties


    【解决方案1】:

    那么……为什么?

    A 而言,Bar 是只读的——你不能从A 调用setter,所以当你请求属性时没有setter 是有道理的A.

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

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

    【讨论】:

      【解决方案2】:

      你可以通过反射设置私有属性,只需使用属性信息中的 SetValue 方法,即使你无法获取 set 方法。

      【讨论】:

        【解决方案3】:

        一般的解决方法是调用

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

        这不是很直观,我同意。

        【讨论】:

        • 也许你需要在这里递归。层次结构可以是任何可能的。
        • 不,除非您在层次结构的某个级别使用new 运算符,否则在为Bar 属性调用DeclaringType 时,您应该始终得到typeof(Foo)。实际上,即使您使用new,它也可能会起作用。
        • 我写了一些代码来证明,是的,你是对的。但是,当我使用“新”运算符时,DeclaringType 不再是 typeof(Foo),它s typeof(A), below was my code(just the hierarchy): class Foo { public string Bar { get;私人套装; } } 类 A : Foo { public new string Bar { get;私人套装; } } B 类:A { }`
        猜你喜欢
        • 2013-09-04
        • 1970-01-01
        • 2015-11-02
        • 2023-03-09
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-23
        相关资源
        最近更新 更多