Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to create a set of classes where a common ancestor is responsible for all the logic involved in setting various properties, and the descendants just change the access of properties depending on whether they are required in the particular descendant.

When I try to do it as shown below I get a compiler error: "cannot change access modifiers when overriding 'protected' inherited member"

Is there a way to achieve what I'm trying to do? Thanks

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; }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this by using "new" instead of "override" to hide the parent's protected property as follows:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...