【发布时间】:2012-10-09 19:52:59
【问题描述】:
我正在研究书中Pro C# and the .NET Platform 中的一个示例,但我在看不到的地方犯了一个错误。程序编译并运行,但此示例中的 Manager 对象没有返回正确的 'StockOptions' 值。为了简洁起见,我将尝试只发布相关代码,因为这个示例都是关于类层次结构的,并且有六个不同的类。 Employee 类中的虚拟方法 GiveBonus 未在 Manager 类中正确覆盖。
class Manager : Employee
{
private int numberOfOpts;
//the properties are inherited from Employee
public int StockOptions { get; set; }
//***METHODS*** this is returns the StockOptions amount as it is in the
// constructor, there's no logic being applied
public override void GiveBonus(float amount)
{
base.GiveBonus(amount);
Random r = new Random();
numberOfOpts += r.Next(500);
}
public override void DisplayStats()
{
base.DisplayStats();
Console.WriteLine("you have {0} stock options", StockOptions);
}
public Manager() { }
public Manager(string fullName, int age, int empID, float currPay,
string ssn, int numbofOpts) : base(fullName, age, empID, currPay, ssn)
{
ID = empID;
Age = age;
Name = fullName;
Pay = currPay;
StockOptions = numbofOpts;
}
}
我的 Main() 方法中的 sn-p
Manager chucky = new Manager("chucky", 50, 92, 100000, "333-33-3333", 9000);
chucky.GiveBonus(300);
chucky.DisplayStats();
Console.WriteLine();
我在提问时犯了一个错误。我应该问的是为什么我必须使用
Console.WriteLine("you have {0} stock options", numbOfOpts);
而不是
Console.WriteLine("you have {0} stock options", StockOptions);
【问题讨论】: