将对象分配给变量

时间:2015-11-18 09:12:48

标签: c#

我有一个带有员工类的简单程序,我在这个班级lyndaalex中有2个对象,我还创建了一个名为CalculateTotalPay()的方法来打印总薪水在简单添加salarybonus后添加到控制台。现在,对于打印到控制台,我有Console.WriteLine("Total Pay = " + totalPay);,但我想进入 Console.WriteLine("Total Pay for " + employeeName " = " + totalPay);但我不想反复向新员工提供新变量,最好的方法是什么?

这是代码

class Employee
{
    public double salary;
    public double bonus;
    public string employeeName;

    public void CalculateTotalPay()
    {
        double totalPay = salary + bonus;
        Console.WriteLine("Total  Pay = " + totalPay);
    }
}
static void Main()
{
    Employee alex = new Employee();
    Employee lynda = new Employee();

    alex.salary = 900000;
    alex.bonus = 20000;
    alex.CalculateTotalPay();

    lynda.salary = 100000;
    lynda.bonus = 20000;
    lynda.CalculateTotalPay();
}

3 个答案:

答案 0 :(得分:2)

首先,你的课应该是这样的:

class Employee
{
    public double Salary { get; set; }
    public double Bonus { get; set; }
    public string Name { get; set; }

    public Employee(String name, double salary, double bonus)
    {
        Salary = salary;
        Bonus = bonus;
        Name = name;
    }

    public void CalculateTotalPay()
    {
        double totalPay = Salary + Bonus;
        Console.WriteLine("Total  Pay for {0} = {1}", Name, totalPay);
    }
}

现在你可以简单地使用构造函数:

Employee alex = new Employee("alex", 900000, 20000);
Employee lynda = new Employee("lynda", 100000, 20000);

编辑:显然你的问题有点不同。 如果您没有外部信息源,则必须在代码中定义所有员工。我会这样推荐:

List<Employee> Employees = new List<Employee>
{
    new Employee("alex", 900000, 20000),
    new Employee("lynda", 100000, 20000)
};

foreach (var employee in Employees) {
        employee.CalculateTotalPay();
}

为了便于阅读,请这样做,并且不要像奖金,工资和名字那样开始制作3个单独的数组。

答案 1 :(得分:0)

您可以使用List<Employee> workers = new List<Employee>();。 添加新员工非常简单 - workers.Add( new Employee {salary = 10, bonus = 100});。 最后你可以对这个系列进行交流:

foreach (var item in workers)
{
    //TODO
}

答案 2 :(得分:0)

我认为您正在寻找以下解决方案。

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<Employee> employees = new List<Employee>
        {
            new Employee("Alex", 900000, 20000),
            new Employee("Lynda", 100000, 20000)
        };

        foreach (var employee in employees)
        {
            employee.CalculatePay();
        }

        Console.ReadKey();
    }
}

public class Employee
{
    private readonly double _salary;
    private readonly double _bonus;
    private readonly string _name;

    public double Salary { get { return _salary; } }
    public double Bonus { get { return _bonus; } }
    public string Name { get { return _name; } }

    public Employee(string name, double salary, double bonus)
    {
        _name = name;
        _salary = salary;
        _bonus = bonus;
    }

    public void CalculatePay()
    {
        double totalPay = Salary + Bonus;
        Console.WriteLine("Total Pay for Employee {0} = {1}", Name, totalPay);
    }
}