0

在你们的帮助下,我想出了这个从 .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].IDEDIT(来自 form2.cs)中获取值,我会得到“当前上下文中不存在客户”。我将如何声明客户以使其在任何地方都可以访问?

谢谢!:)

4

3 回答 3

2

您可以将customers对象传递给Form2或创建一个静态列表。无论哪种方式,它都需要是静态的,因为loadData它是静态的。

为了使其成为静态,在您的 Program.cs 中,您可以执行以下操作:

public static List<Customer> Customers { get; set; }

LoadDatajust do 的第一行:

Form1.Customers = new List<Customer>();

然后任何时候你需要访问它,只需调用Form1.Customers(例如Form1.Customers[1].ID:)

于 2013-10-09T23:01:00.120 回答
1

您的变量在您的班级customers中根本不可见。Form2您需要传递customers给您的类实例Form2(通过自定义构造函数、方法参数或通过设置在Form2类上实现的公共属性/字段来注入它)。

你需要这样的东西:

public partial class Form2 : Form
{
    // add this...
    public List<Customer> Customers
    { 
       get;
       set;
    }

然后,如果你在你的 中创建Form2Program你所做的就是:

Form2 f2 = new Form2(); // supposing you have this already, whatever you named it
f2.Customers = customers; // customers being your variable

如果你是Form2从你的内部创建你的Form1,那么你必须先传递customersForm1,例如。如Adam Plocher您所见(如果您将其设为静态),然后进一步到Form2,但原理保持不变。

附带说明,这不是一个很好的编程实践,但这超出了您的问题范围。

于 2013-10-09T22:58:25.867 回答
0

loadData()is static,所以它看不到非静态实例变量。更改var customersstatic var customers

于 2013-10-09T22:59:32.780 回答