C# 方法B用于方法A;在继承的类中,使用重写的B
例如,在下面的类中,假设C# 方法B用于方法A;在继承的类中,使用重写的B,c#,inheritance,C#,Inheritance,例如,在下面的类中,假设Say()是一个相对较长的方法。其他一切都很好,但我想为GetWords()做些其他事情。我创建一个继承的类,并让GetWords()执行其他操作。但是它的Say()方法仍将使用父类的GetWords() 有没有一种方法可以在不重写继承类中的Say()并复制和粘贴方法体的情况下实现这一点?Dog类已经像那样实现了,但是我可以根据需要随时更改它 Doge d = new Doge(); d.Say(); //says `Rrrrrrrr`. public class Do
Say()
是一个相对较长的方法。其他一切都很好,但我想为GetWords()
做些其他事情。我创建一个继承的类,并让GetWords()
执行其他操作。但是它的Say()
方法仍将使用父类的GetWords()
有没有一种方法可以在不重写继承类中的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";
}
}
在狗身上把单词改成
protected virtual string GetWords()
使用中
protected override string GetWords()
所以您希望它打印出这样的继承?是的,对于这个例子。