listitem中的值不准确

Nag*_*aga 0 c#

我有以下代码应该从来自服务器的字符串生成列表项.代码如下:

foreach (String str in years)
            {

                if (string.IsNullOrEmpty(str) || str.Equals(" "))
                {
                    System.Diagnostics.Debug.WriteLine("empty");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(str);
                    yearLi.Value = str;
                    yearList.Add(yearLi);
                    count = yearList.Count;
                }
                System.Diagnostics.Debug.WriteLine("count-->" + count);

            }
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,如果字符串数组"years"有{2011,2012},那么列表应该是2011年和2012年.但它有2012,2012.我无法在此代码中找到错误.请指教.

Mat*_*and 8

yearLi通过循环在每个循环中重用相同的对象.当你这样做:

yearList.Add(yearLi);
Run Code Online (Sandbox Code Playgroud)

您每次都添加相同的对象.当你在下一次循环中更改它时,你将在列表的每个单元格中更改它(因为它都是对同一对象的引用).

你需要yearLi在循环中实例化一个新的(无论应该是什么类).