【问题标题】:How to extend a class and override a method which is from interface?如何扩展一个类并覆盖一个来自接口的方法?
【发布时间】:2017-10-21 19:34:37
【问题描述】:

我有以下场景:

  • 接口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。

有什么帮助吗?

【问题讨论】:

  • 您应该将Rectangle 中的Draw 方法标记为virtual 以便能够在派生类中覆盖它

标签: c# oop inheritance interface


【解决方案1】:

Rectangle.Draw 虚拟,Square.Draw 覆盖

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

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

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2013-01-19
    • 2010-10-13
    相关资源
    最近更新 更多