简体   繁体   English

如何扩展类并重写来自接口的方法?

[英]How to extend a class and override a method which is from interface?

I have the following scenario: 我有以下情况:

  • interface IShape defines method Draw . IShape接口定义方法Draw
  • class Circle implements IShape and the method Draw . Circle类实现IShape和方法Draw
  • class Rectangle implements IShape and the method Draw . Rectangle类实现IShape和方法Draw
  • class Square extends Rectangle and overrides the method Draw . Square类扩展Rectangle并重写Draw方法。

I wrote the code as following for the above scenario: 对于上述情况,我编写了以下代码:

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

I am unable to get the last scenario which is class Square extends Rectangle and overrides the method Draw . 我无法获得最后一个场景,该场景是class Square extends Rectangle and overrides the method Draw

Any help? 有什么帮助吗?

Rectangle.Draw virtual, Square.Draw override 虚拟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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何重写从基类继承的方法,该方法又从接口实现该方法? - How to override a method inherited from a base class, which in turn implemented it from an interface? 如何协变/逆变重写从接口实现的虚方法? - How to covariant/contravariant in override virtual method which implements from interface? 派生的 class 如何覆盖 base 的 class 接口方法 - How does derived class override base's class interface method 在C#中如何从派生类实例调用已经在派生类中覆盖的基类方法 - in C# how to invoke base class method, which already override in derived class, from derived class instance 从显式实现接口的基类重写方法 - Override a method from a base class that explicitly implements an interface 如何隐藏从基类派生的类中的方法,该方法是基类中接口实现的一部分? - How to hide a method, which is part of an interface implementation within a base class, from classes that derive from the base class? Linq如何扩展\\覆盖现有的toList()方法 - Linq how to Extend\Override existing toList() Method 覆盖接口方法,但使用派生 class 的参数 - Override an interface method but using argument of a derived class 覆盖派生类中显式实现的接口方法 - Override explicitly implemented interface method in derived class 类中的方法签名扩展了通用类 - Method signatures in classes which extend a generic class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM