您正在创建的Test
Test test = new Test(); // This is your instance
IList<Test> myList = new List<Test>();
foreach (DataRow dataRow in dataTable.Rows)
{
// Here you change the values of the existing instance each time you loop
test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
test.LastName = dataRow.ItemArray[1].ToString();
test.FirstName = dataRow.ItemArray[2].ToString();
myList.Add(test); // but you are still just adding the same reference to the list multiple times
}
一个实例,然后因为你永远不会创建一个新的Test
实例,你多次添加相同的参考名单。这意味着您基本上只是一遍又一遍地存储同一个对象:如果您对列表中的一个项目进行任何更改,它将立即在所有其他项目中可见,因为它们本质上是相同的对象
解决方案是移动测试循环中的实例
IList<Test> myList = new List<Test>();
foreach (DataRow dataRow in dataTable.Rows)
{
Test test = new Test(); // Each loop iteration will now create a new instance of Test
test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
test.LastName = dataRow.ItemArray[1].ToString();
test.FirstName = dataRow.ItemArray[2].ToString();
myList.Add(test);
}
如果您需要了解这更好,看看.NET参考和值类型和引用/值传递
价值和文献类型.NET: http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
有关维基百科上指针的一些信息 http://en.wikipedia.org/wiki/Pointer_(computer_programming)
http://msdn.microsoft.com/en-us/library/490f96s2。aspx –
您遇到的问题是因为该测试是引用类型而不是值类型,当您将测试添加到列表时,您正在添加指向内存测试的指针,然后运行下一个循环时,您将进行更改该内存空间覆盖前一个循环的数据,因此你需要使用循环内的New statment来为该循环分配一个新的内存空间来使用 – MikeT
感谢所有感谢指出我的错误:) – Optimus