2017-10-21 54 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(); 
    } 
}