我想知道如何在 C# 中将值从数组传递和存储到类对象。
这是我的主要程序代码
public partial class Form1 : Form
{
List<Configuration> lines = new List<Configuration>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
//Read in every line in the file
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string textfile = line;
string[] array = new string[] { "\\n" };
string[] parts = textfile.Split(array, StringSplitOptions.RemoveEmptyEntries);
///////////////////////////////////////////////////
for (int i = 0; i < parts.Length; i++)
{
lines.Add(new Configuration(parts[i],0));
}
//lines.Add(new Configuration(line));
//listBox1.Items.Add(line);
}
}
listBox1.DataSource = lines;
listBox1.DisplayMember = "CompanyName";
}
}
我的班级目标代码
class Configuration
{
string _CompanyName;
int _Employees;
public Configuration(string companyname, int number_of_Employees)
{
_CompanyName = companyname;
_Employees = number_of_Employees;
}
//program properties and validation
public string CompanyName
{
set
{
_CompanyName = value;
}
get
{
return _CompanyName;
}
}// End of levelname validation
//program properties and validation
public int EmployeesNumber
{
set
{
_Employees = value;
}
get
{
return _Employees;
}
}// End of levelname validation
}
目前,该程序读取一个文本文件,其中包含公司列表和每家公司的员工人数。像这样的结构
Microsoft\n92200
Google\n33077
Apple\n60400
IBM\n426751
Facebook\n3000
当程序运行时,它将公司名称和员工人数分成一个数组。该部分工作正常,它只是将所有内容存储到 String companyName 中。当我尝试修改它以将值存储在类对象的不同字段中时,我会出错。