如何增加属性的访问修饰符

Wil*_*Cau 10 c# oop polymorphism

我正在尝试创建一组类,其中共同的祖先负责设置各种属性所涉及的所有逻辑,后代只是根据特定后代是否需要来更改属性的访问权限.

当我尝试如下所示执行此操作时,我收到编译器错误:"覆盖'受保护'继承成员时无法更改访问修饰符"

有没有办法实现我想要做的事情?谢谢

public class Parent
{
     private int _propertyOne;
     private int _propertyTwo;

     protected virtual int PropertyOne
     {
          get { return _propertyOne; }
          set { _propertyOne = value; }
     }

     protected virtual int PropertyTwo
     {
          get { return _propertyTwo; }
          set { _propertyTwo = value; }
     }
}

public class ChildOne : Parent
{
    public override int PropertyOne  // Compiler Error CS0507
    {
        get { return base.PropertyOne; }
        set { base.PropertyOne = value; }
    }
    // PropertyTwo is not available to users of ChildOne
}

public class ChildTwo : Parent
{
    // PropertyOne is not available to users of ChildTwo
    public override int PropertyTwo  // Compiler Error CS0507
    {
        get { return base.PropertyTwo; }
        set { base.PropertyTwo = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*lio 11

您可以使用"new"而不是"override"来隐藏父级的受保护属性,如下所示:

public class ChildOne : Parent
{
    public new int PropertyOne  // No Compiler Error
    {
        get { return base.PropertyOne; }
        set { base.PropertyOne = value; }
    }
    // PropertyTwo is not available to users of ChildOne
}

public class ChildTwo : Parent
{
    // PropertyOne is not available to users of ChildTwo
    public new int PropertyTwo
    {
        get { return base.PropertyTwo; }
        set { base.PropertyTwo = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • OOPS ..秒更快:) ..无论如何使用new与覆盖不一样; 新隐藏了父成员,这种方式不再是多态性. (2认同)

Mar*_*ell 5

您无法更改访问权限,但可以通过更大的访问权限重新声明该成员:

public new int PropertyOne
{
    get { return base.PropertyOne; }
    set { base.PropertyOne = value; }
}
Run Code Online (Sandbox Code Playgroud)

问题是这是一个不同的 PropertyOne,继承/虚拟可能无法按预期工作.在上面的情况下(我们只是调用base.*,而新方法不是虚拟的)可能没问题.如果需要真正的多态以上这一点,则无法在不引入中间类做(AFAIK)(由于不能newoverride在同一类型相同的构件):

public abstract class ChildOneAnnoying : Parent {
    protected virtual int PropertyOneImpl {
        get { return base.PropertyOne; }
        set { base.PropertyOne = value; }
    }
    protected override int PropertyOne {
        get { return PropertyOneImpl; }
        set { PropertyOneImpl = value; }
    }
}
public class ChildOne : ChildOneAnnoying {
    public new int PropertyOne {
        get { return PropertyOneImpl; }
        set { PropertyOneImpl = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的重点是仍然有一个虚拟成员覆盖:PropertyOneImpl.