2017-02-25 122 views
1

例如,在下面的类中,假设Say()是一个相对较长的方法。其他一切都很好,但我想为GetWords()做点别的事情。我创建了一个继承类,并使GetWords()做别的。但其Say()方法仍将使用父类的GetWords()方法B用于方法A;在继承类中,使A被覆盖B

有没有办法在继承类中复制并粘贴方法体而不覆盖Say()Dog类已经实现了,但我可以根据需要随时更改它。

Doge d = new Doge(); 
d.Say(); //says `Rrrrrrrr`. 

public class Dog 
{ 
    public void Say() 
    { 
     // Do a lot of stuff 
     var words = GetWords(); 
     Debug.WriteLine(words); 
     // Do a lot of other stuff 
    } 

    protected string GetWords() 
    { 
     return "Rrrrrrrr"; 
    }  
} 

public class Doge:Dog 
{ 
    protected new string GetWords() 
    { 
     return "Such inheritance"; 
    }  
} 
+0

所以,你希望它打印出来'这样的inheritance'? –

+0

是的,对于这个例子。 –

回答

1

在狗的变化GetWords到

protected virtual string GetWords() 

在公爵使用

protected override string GetWords() 
相关问题