C#数组来保存数据

本文关键字:数据 保存 数组 | 更新日期: 2023-09-27 17:57:44

我是C#的新手,遇到了一个问题。事实上,这是我在大学和编程的第一年,我对数组有一个问题。我在Windows窗体应用程序中创建了一个包含3个构造函数和1个方法的类。问题是,我想使用一个按钮将用户正在键入的三个文本框中的数据存储到一个10的数组中。我不知道怎么做。

public class Employee
{
    private int idnum;
    private string flname;
    private double annual;
    public Employee()
    {
        idnum = 0;
        flname = "";
        annual = 0.0;
    }
    public Employee(int id, string fname)
    {
        idnum = id;
        flname = fname;
        annual = 0.0;
    }
    public Employee(int id, string fname, double ann)
    {
        idnum = id;
        flname = fname;
        annual = ann;
    }
    public int idNumber
    {
        get { return idnum; }
        set { idnum = value; }
    }
    public string FLName
    {
        get { return flname; }
        set { flname = value; }
    }
    public double Annual
    {
        get { return annual; }
        set { annual = value; }
    }
    public string Message()
    {
        return (Convert.ToString(idnum) + "  " + flname + "  " + Convert.ToString(annual));
    }
}

C#数组来保存数据

首先,您应该在此表单上添加3个textboxe元素,并以下一种方式命名为textBoxId、textBoxFLName、textBoxAnnual

你还必须添加一个按钮。我们称之为btnSave为该按钮编写OnClick事件。在这种方法中,我们必须读取用户在表格上填写的所有数据

List<Employee> allEmployees = new List<Employee>();
private void buttonSave_Click(object sender, EventArgs e)
    {
        //read user input
        int empId = Int32.Parse(textBoxId.Text);
        string empFlName = textBoxFLName.Text;
        double empAnnual = double.Parse(textBoxAnnual.Text);
        // create new Employee object
        Employee emp = new Employee(empId, empFlName, empAnnual);
        // add new employee to container (for example array, list, etc). 
        // In this case I will prefer to use list, becouse it can grow dynamically
        allEmployees.Add(emp);
    }

你也可以用最短的方式重写你的代码:

public class Employee
{
    public int IdNum { get; set; }
    public string FlName { get; set; }
    public double Annual { get; set; }
    public Employee(int id, string flname, double annual = 0.0)
    {
        IdNum = id;
        FlName = flname;
        Annual = annual;
    }
    public override string ToString()
    {
       return (Convert.ToString(IdNum) + "  " + FlName + "  " + Convert.ToString(Annual));
    }
}