我正在研究书中的一个例子,但Pro C# and the .NET Platform
我在看不到的地方犯了一个错误。程序编译并运行,但Manager
此示例中的对象没有返回正确的“StockOptions”值。为了简洁起见,我将尝试只发布相关代码,因为这个示例都是关于类层次结构的,并且有六个不同的类。类中的虚拟方法未GiveBonus
在Employee
类中正确覆盖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() 方法的片段
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);