2017-10-21 52 views
0

我有以下情形:如何扩展一个类并覆盖来自接口的方法?

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

任何帮助?

+4

你应该标志着''中Rectangle' Draw'方法'virtual'能够覆盖它在派生类 – Fabio

回答

4

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