从嵌套类访问外部类隐藏的基本属性

Gio*_*rgi 2 c# inheritance nested-class

假设我有一个类,它有一个隐藏它的基本属性的属性,并且在这个类中有一个嵌套类.是否可以从嵌套类访问base hidden*virtual*属性?

这是一个例子:

class BaseClass
{
    protected virtual String SomeProperty {get; set;}
}

class Inherited : BaseClass
{
    protected new String SomeProperty {get; set;}

    class Nested
    {
        Inherited parent;
        public Nested(Inherited parent)
        {
            this.parent = parent;
        }

        public void SomeMethod()
        {
            //How do I access the SomeProperty which belongs to the BaseClass? 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一解决方案是向Inherited类添加一个私有方法,返回base.SomeProperty是否有更好的解决方案?

Nuf*_*fin 5

你可以投射你的InheritedClass参考BaseClass.由于您隐藏了基本属性而不是覆盖它,这应该可以解决问题.

public void SomeMethod()
{
    BaseClass baseRef = parent;
    // do stuff with the base property:
    baseRef.SomeProperty = someValue;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

为了使这个工作,嵌套类的SomeProperty属性BaseClass必须是通过创建它internal(如果你不想在声明程序集之外访问属性)或protected internal(如果你想允许覆盖派生类)从其他集会).

如果两个选项都是不受限制的(即,当您的派生类已经在另一个程序集中时),您将无法声明包装器属性.

private string SomeBaseProperty
{
    get
    {
        return base.SomeProperty;
    }

    set
    {
        base.SomeProperty = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这导致编译器错误CS1540:无法通过类型'type1'的限定符访问受保护的成员'member'; 限定符必须是'type2'类型(或从中派生出来)http://msdn.microsoft.com/en-us/library/s9zta243.aspx (2认同)