![](/img/trans.png)
[英]Getting the largest value from an object in a list in another list [C#]
[英]Getting value from list in C#
在你們的幫助下,我想到了這段代碼,該代碼從.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)中獲取價值,則會得到“在當前上下文中不存在客戶”。 我將如何聲明客戶使其可以在任何地方訪問?
謝謝! :)
您可以將customers
對象傳遞給Form2
或創建靜態列表。 無論哪種方式,它都必須是靜態的,因為loadData
是靜態的。
要使其靜態,可以在Program.cs中執行以下操作:
public static List<Customer> Customers { get; set; }
在LoadData
的第一行上,只需執行以下操作:
Form1.Customers = new List<Customer>();
然后,只要您需要訪問它,就稱為Form1.Customers
(例如: Form1.Customers[1].ID
)
customers
變量在Form2
類中根本不可見。 您需要將customers
傳遞到Form2
類的實例(通過自定義構造函數,方法參數或通過設置在Form2
類上實現的公共屬性/字段來注入它)。
您需要這樣的東西:
public partial class Form2 : Form
{
// add this...
public List<Customer> Customers
{
get;
set;
}
然后,如果您在Program
創建Form2
,您將執行以下操作:
Form2 f2 = new Form2(); // supposing you have this already, whatever you named it
f2.Customers = customers; // customers being your variable
如果要從Form1
創建Form2
,則必須首先將customers
傳遞給Form1
,例如。 正如Adam Plocher
向您展示的(如果您將其設置為靜態的),然后進一步介紹給Form2
,但是原理保持不變。
附帶說明,這不是一個很好的編程習慣,但這超出了您的問題范圍。
loadData()
是static
,因此看不到非靜態實例變量。 將var customers
更改為static var customers
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.