简体   繁体   中英

How to override parts of a method of a base class in C#

I have Class B that derives from Class A .

How can I override parts of Draw method in Class A and keep parts of it and throw away the rest?

For example here I want the Draw method in Class B to DrawRectangles() and instead of DrawrCircles to DrawTriangles .

public class A
{
    public virtual void Draw()
    {
       DrawRectangles();
       DrawCircles();
    }
}

public class B : A
{
    public override void Draw()
    {
        // I want to still draw rectangles
        // but I do not want to draw circles
        // I want to draw triangles instead
    }
}

Then why don't you just call the methods you want to execute ?

public override void Draw()
{
     DrawRectangles();
     DrawTriangles();
}

There is no partially overriding for methods.You can declare partial methods but they are not the same.If you want to override, you need to overrride whole method.

I would suggest you to go with the below:

public class A
{
    public virtual void OverridableDraw()
    {
        DrawCircles();  // declare all those which can be overrided here
    }
    public void Draw()
    {
        DrawRectangles(); // declare methods, which will not change
    }
}
public class B : A
{
    public override void OverridableDraw()
    {
        // just override here
    }
}

The Idea is to override only those, which tends to change.

Then, you can call both the methods.

OverridableDraw();
Draw();

As an alternative design, if you have lots of different 'parts' you have to draw, and have not so much alternate drawing, I'd personally use a [Flag] enumeration

[Flags]
public enum DrawParts
{
    Rectangles = 1,
    Circles = 2,
    Triangles = 4,
    //etc
}
public class A
{
    //or a regular get/setter instead of a virtual property
    public virtual DrawParts DrawMode { get { return DrawParts.Rectangles | DrawParts.Circles; } } 
    public void Draw()
    {
        var mode = DrawMode;
        if (mode.HasFlag(DrawParts.Circles))
            DrawCircles();
        if (mode.HasFlag(DrawParts.Rectangles)) //NB, not elseif
            DrawRectangles();
        //etc
    }

}

public class B : A
{
    public override DrawParts DrawMode{get{return DrawParts.Rectangles | DrawParts.Triangles; }}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM