在大家的幫助下,我想出了這個代碼,它從.txt文件加載數據庫,並使用這些值填充列表。我在使用列表獲取值時遇到了一些麻煩。繼承人在我的Program.cs從C#中的列表中獲取價值
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
編輯獲得的價值(從form2.cs) ,我得到「在當前情況下客戶不存在」。我如何宣佈客戶可以在任何地方訪問?
謝謝! :)
作爲C#中的noob,這個答案很容易理解,我認爲它正是我想要的。我現在距離C#掌握更近了一步! ;) – Nathan