gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:45:00 25 4
gpt4 key购买 nike

我有以下场景:

  • 接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com