如何扩展一个类并覆盖一个来自接口的方法?

时间:2017-10-21 19:34:37

标签: c# oop inheritance interface

我有以下情况:

  • interface IShape定义方法Draw
  • 班级Circle实施IShape和方法Draw
  • 班级Rectangle实施IShape和方法Draw
  • Square扩展Rectangle并覆盖方法Draw

我为以上场景编写了如下代码:

class Program
{
    static void Main(string[] args) { }
}

public interface IShape
{
    void Draw();
}

public class Circle : IShape
{
    public void Draw()
    {
        throw new NotImplementedException();
    }
}

public class Rectangle : IShape
{
    public void Draw()
    {
        throw new NotImplementedException();
    } 
}

public class Square : Rectangle
{
    public virtual void Draw()
    {
        throw new NotImplementedException();
    }
}

我无法获得class Square extends Rectangle and overrides the method Draw的最后一个场景。

任何帮助?

1 个答案:

答案 0 :(得分:5)

Rectangle.Draw virtual,Square.Draw override

public class Rectangle : IShape
{
    public virtual void Draw()
    {
        throw new NotImplementedException();
    } 
}

public class Square : Rectangle
{
    public override void Draw()
    {
        throw new NotImplementedException();
    }
}