好的,在我学习的过程中请耐心等待。这是我的问题。
我不明白为什么我不能覆盖父类的方法。这是基类的代码(是的,我从 OOP 书中窃取了 Java 代码,并试图用 C# 重写它)。
using System;
public class MoodyObject
{
protected String getMood()
{
return "moody";
}
public void queryMood()
{
Console.WriteLine("I feel " + getMood() + " today!");
}
}
这是我继承基类 (MoodyObject) 的其他 2 个对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class SadObject: MoodyObject
{
protected String getMood()
{
return "sad";
}
//specialization
public void cry()
{
Console.WriteLine("wah...boohoo");
}
}
}
和:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class HappyObject: MoodyObject
{
protected String getMood()
{
return "happy";
}
public void laugh()
{
Console.WriteLine("hehehehehehe.");
}
}
}
这是我的主要内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MoodyObject moodyObject = new MoodyObject();
SadObject sadObject = new SadObject();
HappyObject happyObject = new HappyObject();
Console.WriteLine("How does the moody object feel today?");
moodyObject.queryMood();
Console.WriteLine("");
Console.WriteLine("How does the sad object feel today?");
sadObject.queryMood();
sadObject.cry();
Console.WriteLine("");
Console.WriteLine("How does the happy object feel today?");
happyObject.queryMood();
happyObject.laugh();
}
}
}
如您所见,非常基本的东西,但这是输出:
How does the moody object feel today? I feel moody today!
How does the sad object feel today? I feel moody today! wah...boohoo
How does the happy object feel today? I feel moody today! hehehehehehe. Press any key to continue . . .
不是我想象的那样。我试图使基方法成为虚拟的,并在尝试覆盖它时调用覆盖,这只会让我得到这个错误“无法覆盖继承的成员‘MoodyObject.getMood()’,因为它没有被标记为虚拟、抽象或覆盖”。我也在没有虚拟和覆盖的情况下尝试过它,它认为我正在尝试隐藏基本方法。同样,我是 OOP 的新手,非常感谢任何指导。
编辑添加:我找到了! MoodyObject.cs 只是解决方案资源管理器中的一个“解决方案项目”,而不是“ConsoleApplication1”项目。我将它拖到解决方案资源管理器中它所属的位置,瞧!现在可以了。我在下面将 Luc 的回答标记为答案,因为他提供了我需要的帮助,帮助我解决问题……我在这里学到了很多东西。太棒了,你们这些家伙和女孩们都非常聪明!
最佳答案
在 C# 中,默认情况下方法不是虚拟的,因此如果您将某些方法设计为可重写的,则应将其指定为虚拟的:
class Base
{
protected virtual string GetMood() {...}
}
其次,您必须指定要在派生类中覆盖基类的方法。
class Derived : Base
{
protected override string GetMood() {...}
}
如果您不指定“override”关键字,您将获得隐藏基类型的方法(编译器会警告您为该方法添加“new”关键字以明确说明)。
如果你想停止继承链并禁止进一步覆盖该方法,你应该将方法标记为密封的,如下所示:
protected sealed override string GetMood() {...}
关于c# - C# 中的重写和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/337598/