我正在尝试创建一组类,其中共同的祖先负责设置各种属性所涉及的所有逻辑,而后代只是根据特定后代是否需要更改属性的访问权限。
当我尝试如下所示执行此操作时,出现编译器错误:“在覆盖‘ 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/