简体   繁体   中英

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:

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:

    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}:

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 ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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