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

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

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

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

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”来隐藏父级的受保护属性,如下所示:

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

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

 public new int PropertyOne { get { return base.PropertyOne; } set { base.PropertyOne = value; } } 

问题是这是一个不同的 PropertyOne ,inheritance/虚拟可能无法按预期工作。 在上面的情况下(我们只是调用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; } } } 

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

没有。 你仍然可以用你的隐藏inheritance的属性

 public class ChildTwo: Praent { public new int PropertyTwo { // do whatever you want } } 

ps:这不再是虚拟/覆盖关系(即没有多态调用)