C#抽象类派生函数没有回归期望

时间:2015-08-27 02:37:51

标签: c# class

我简要介绍一下Abstract Classes。我用于这些类的代码是:

namespace ELog
{
    abstract class ELog
    {
        public string Name { get; set; }
        public int ID { get; set; }

        public abstract double MonthlySalary();

        public string Information()
        {
            return String.Format("{0} (ID: {1}) earns {3} per month.", Name, ID, MonthlySalary()); //Code to print out general information.
        }
    }

    class PermanentEmployee : ELog
    {
        public double WagePerAnnum { get; set; }

        public PermanentEmployee(string Name, int ID, double WagPerAnnum)
        {
            this.Name = Name;
            this.ID = ID;
            this.WagePerAnnum = WagePerAnnum;
        }

        public override double MonthlySalary()
        {
            return WagePerAnnum / 12;  //Returning 0 when I use .MonthlySalary()
        }
    }
}

尽管WagePerAnnum设置为任何>,MonthlySalary函数似乎返回0 12.我正在使用此代码执行,它也返回格式异常:

PermanentEmployee PE1 = new PermanentEmployee("Stack", 0, 150000);
Console.WriteLine(PE1.MonthlySalary()); // Returns 0 when should return 150000 / 12 = 12,500
Console.WriteLine(PE1.Information()); //Format Exception Here.

2 个答案:

答案 0 :(得分:5)

拼写错误。简单,简单的拼写错误:

在构造函数中WagPerAnnum中缺少'e':

    public PermanentEmployee(string Name, int ID, double WagPerAnnum)
    {
        this.Name = Name;
        this.ID = ID;
        this.WagePerAnnum = WagPerAnnum;
    }

对于您的例外,您跳过{2}并转到{3}:

String.Format("{0} (ID: {1}) earns {2} per month.", Name, ID, MonthlySalary()); //Code to print out general information.

答案 1 :(得分:1)

public PermanentEmployee(string Name, int ID, double WagPerAnnum)
{
    this.Name = Name;
    this.ID = ID;
    // You want WagPerAnnum (the parameter)
    // and not WagePerAnnum (the property)
    this.WagePerAnnum = WagePerAnnum;
}

通常这会是编译失败,但你很幸运; - )