关于引用类型和值类型一点体会


有List数据结构如下:

Name Number
A 2
A 3
B 7

现在需要把Name相同的项合并,Number累加,就是下表:

Name   Number
A 5
B 7

虽然逻辑可以控制List无重复项,为了保险,我选择用Dictionary作为中间对象来实现功能,代码如下:

 1         public List MergeData(List dataList)
 2         {
 3             List targetList= new List();
 4             Dictionary<string, Item> tempDic= new Dictionary<string, Item>();
 5             Item item;
 6             for (int i = 0; i < dataList.Count; i++)
 7             {
 8                 item= dataList[i];
 9                 if (tempDic.Keys.Contains(item.Name))
10                 {
11                     tempDic[item.Name].Number+= item.Number;
12                 }
13                 else
14                 {
15                     tempDic.Add(item.Name,item.Number);
16                 }
17             }
18             if (!Utility.isNullOrEmpty(resultDic))
19             {
20                 foreach (Item resultItem in tempDic.Values)
21                 {
22                     targetList.Add(resultItem);
23                 }
24             }
25             return targetList;
26         }


运行的结果如下:

targetList打印输出的结果是期望的结果:

Name   Number
A 5
B 7

但是原dataList变成了:

Name   Number
A 5
A 3
B 7

这里的问题就出在Line 8 >>  item=dataList[i];

C#是引用类型,看起来,我们在For循环的Line 11把 Dictionary的Key为A的Value(Item)的Number累加了一次,变成了5,这没有一点问题,可是由于Item是一个对象,类型是Object,属于引用类型,所以原List中的第一个对象A的值Number也变成了5

C