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

标签 c# oop polymorphism

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

当我尝试如下所示执行此操作时,出现编译器错误:“在覆盖‘ protected ’继承成员时无法更改访问修饰符”

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

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; }
    }
}

最佳答案

您可以通过使用“new”而不是“override”来隐藏父级的 protected 属性,如下所示:

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; }
    }
}

关于c# - 如何增加属性的访问修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886977/

相关文章:

c# - 机器人框架 : Why can't I use SendAsync?

java - 这个java设计模式的名字是什么?

c++ - 如何使用多态性使复合对象成为派生类的全局对象?

java - 什么时候应该使用工厂方法模式? (而不是组合)

c# - 如何在 Azure 开发测试实验室中部署 Selenium Grid

c# - StackPanel 内的 StackPanel 对齐不正确

c# - 如何在 C# 中执行原子写入/追加,或者如何使用 FILE_APPEND_DATA 标志打​​开文件?

java - 实现中 "optional"方法的接口(interface)隔离原则

php - 数据库中许多主表的公共(public)子表

c++ - std::unique_ptr 中的抽象类作为函数的返回不起作用