c# - 如何扩展类并覆盖来自接口(interface)的方法?

标签 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 override the method Draw

有什么帮助吗?

最佳答案

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

关于c# - 如何扩展类并覆盖来自接口(interface)的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46867254/

相关文章:

c# - 转换压缩 COBOL

oop - Scala 不可变与可变。一个人应该走的路是什么?

c++ - 覆盖在祖 parent 的构造函数中调用的祖 parent 的虚拟方法

matlab - 与父类(super class)和子类构造函数交互

c# - 使用 C# 从 xml 读取子元素

c# - VS2012无管理员账号远程调试

c# - 效率 : Creating an array of doubles incrementally?

php - 从父类调用扩展类函数

java - 对象数组的初学者混淆

java - 什么算法在只有 < 的静态方法中运行 T 类型定义?超T> <?扩展 T> 参数?