I'm trying to create a list and insert values in to it. But when I add a new item it changes all existing items in the list to the same value I add and I don't understand why.
Here is my code:
public List<Times> CreateListOfTimes()
{
var listOfTimes = new List<Times>();
var times = new Times();
int startTime = 8;
int endTime = startTime + 1;
for (int i = 0; i < 8; i++)
{
times.StartTime = startTime;
times.EndTime = endTime;
listOfTimes.Add(times);
startTime++;
endTime++;
}
return listOfTimes;
}
Run Code Online (Sandbox Code Playgroud)
The first time I add a value to times, times.StartTime = 8 and times.EndTime = 9. When I loop the second time I add 9 and 10 but i also change the already added 8 and 9 to 9 and 10. Why does it happen and how can I fix it?
Its because its the same Times object every time, you have to make a new one in the loop:
for (int i = 0; i < 8; i++)
{
var times = new Times();
times.StartTime = startTime;
times.EndTime = endTime;
listOfTimes.Add(times);
startTime++;
endTime++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |