创建多个实例并设置 属性 值

Creating multiple instances and setting property values

我正在访问一个 .CSV 文件并将值转换为在 DataGrid 中显示,我的问题是我只有一个定义的实例并且它曾经在循环之外并且我没有设置它的属性。

我如何在循环中创建多个实例并设置 属性 值?

CSV 格式为: 'header' 'string,string,int,string'(最多 300 个条目)

这是主要代码,通过单击“菜单”->“打开”调用:

        // Function to open a .CSV file and assign the values within to a List.
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        List<Stock> stocks = new List<Stock>();
        // Set strings to retrieve current directory and store stocklist.csv as "filename"
        string filename = @"C:\StockFile\stocklist.csv";

        // Read all lines in file and set indexer to 0.
        string[] linesInFile = File.ReadAllLines(filename);
        string[] StockDetails = new string[0];

        for (int i = 1; i < linesInFile.Length; i++)
        {
            // Load lines in file and increment by 1.
            string currentLine1 = linesInFile[i];
            // Split the current line by separator ,
            StockDetails = currentLine1.Split(',');

            Stock item = new Stock();
            stocks.Add(item);
        }
        var list = new BindingList<Stock>(stocks);
        stockGridView.DataSource = list;
    }

这是我的库存 class:

    class Stock
    {
        public string Code { get; internal set; }
        public string Desc { get; internal set; }
        public int CurCnt { get; internal set; }
        public string Order { get; internal set; }

        public Stock(string code, string desc, int curcnt, string order)
        {
            Code = code;
            Desc = desc;
            CurCnt = curcnt;
            Order = order;
        }
    }

如果我明白你在做什么,你需要初始化 Stock 项目的实例,并且每次在循环中 new 关键字都会创建一个新的实例并将创建的实例添加到列表中

 private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        List<Stock> stocks = new List<Stock>();
        // Set strings to retrieve current directory and store stocklist.csv as "filename"
        string filename = @"C:\StockFile\stocklist.csv";

        // Read all lines in file and set indexer to 0.
        string[] linesInFile = File.ReadAllLines(filename);
        string[] StockDetails = new string[0];

        for (int i = 1; i < linesInFile.Length; i++)
        {
            // Load lines in file and increment by 1.
            string currentLine1 = linesInFile[i];
            // Split the current line by separator ,
            StockDetails = currentLine1.Split(',');

        Stock item = new Stock(StockDetails[0],StockDetails[1],StockDetails[2],StockDetails[3]);
    stocks.Add(item);
        }
        var list = new BindingList<Stock>(stocks);
        stockGridView.DataSource = list;
    }