[英]C# array to save data
我是C#的新手,但我遇到了问题。 实际上,这是我上大学和编程的第一年,我对数组有疑问。 我在Windows Form Application中制作了一个包含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));
}
}
首先,您应该在此表单上添加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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.