在你们的帮助下,我想出了这个从 .txt 文件加载数据库并用值填充列表的代码。我在实际使用列表来获取值时遇到了一些麻烦。这是我的 Program.cs 中的代码
static class Program
{
var customers = new List<Customer>();
static void loadData() //Load data from Database
{
string[] stringArray = File.ReadAllLines("Name.txt");
int lines = stringArray.Length;
if (!((lines % 25) == 0))
{
MessageBox.Show("Corrupt Database!!! Number of lines not multiple of 25!");
Environment.Exit(0);
}
for(int i = 0;i<(lines/25);i++){
customers.Add(new Customer
{
ID=stringArray[(i*25)],
Name = stringArray[(i * 25) + 1],
Address = stringArray[(i * 25) + 2],
Phone = stringArray[(i * 25) + 3],
Cell = stringArray[(i * 25) + 4],
Email = stringArray[(i * 25) + 5],
//Pretend there's more stuff here, I'd rather not show it all
EstimatedCompletionDate = stringArray[(i * 25) + 23],
EstimatedCompletionTime = stringArray[(i * 25) + 24]
});
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
loadData();
Application.Run(new Form1());
}
}
以及来自 class1.cs 的代码 - Customer 类
public class Customer
{
public string ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Cell { get; set; }
public string Email { get; set; }
//Pretend there's more stuff here
public string EstimatedCompletionDate { get; set; }
public string EstimatedCompletionTime { get; set; }
}
但是,如果我尝试从customers[1].ID
EDIT(来自 form2.cs)中获取值,我会得到“当前上下文中不存在客户”。我将如何声明客户以使其在任何地方都可以访问?
谢谢!:)