简体   繁体   English

C#抽象类派生函数未返回期望

[英]C# Abstract Class Derived Function Not Returning Expectation

I am briefly looking at Abstract Classes. 我简要地看了抽象类。 The code I am using for the classes is: 我用于这些类的代码是:

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()
        }
    }
}

The MonthlySalary function seems to be returning 0 despite WagePerAnnum being set to anything > 12. I am using this code to execute which returns a Format Exception too: 尽管WagePerAnnum设置为大于12的值,MonarySalary函数似乎仍返回0。我正在使用以下代码执行该操作,该代码也返回格式异常:

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.

Spelling mistakes. 拼写错误。 Plain, simple spelling mistakes: 简单的拼写错误:

There a missing 'e' in WagPerAnnum in you constructor: 构造函数中WagPerAnnum中缺少“ e”:

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

For your exception, you skipped {2} and went to {3}: 出于例外,您跳过了{2}并转到了{3}:

String.Format("{0} (ID: {1}) earns {2} per month.", Name, ID, MonthlySalary()); //Code to print out general information.
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;
}

Normally this would be a compile failure, but you're just lucky ;-) 通常这会导致编译失败,但是您很幸运;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM