码迷,mamicode.com
首页 > 其他好文 > 详细

C#基础之集合1

时间:2014-08-24 23:26:43      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   使用   io   数据   ar   

1.C#中集合用处无处不在,可是对于类似于小编这样的初学者在初次使用集合会遇到一些小问题.话不多说,看看代码。

code:

bubuko.com,布布扣
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace CnBog20140824
 7 {
 8     public class Program
 9     {
10         public static void Main(string[] args)
11         {
12             string str = "123";
13             List<string> lstStr = new List<string>();
14             lstStr.Add(str);
15             str = "213";
16             lstStr.Add(str);
17 
18             string[] array = new string[1];
19             array[0] = "张三";
20             List<string[]> lstArray = new List<string[]>();
21             lstArray.Add(array);
22             array[0] = "李四";
23             lstArray.Add(array);
24 
25             Console.ReadKey();
26         }
27     }
28 }
View Code

 输出结果:通过变量快速监控,我们来看看集合的内容,对于lstStr类容已经发生变化了,可是对于lstArray虽然后面修改了数组的内容可是lstArray的每个元素都变成后面被修改的内容了。

bubuko.com,布布扣    bubuko.com,布布扣

 原因分析:学过C/C++的都知道,变量分为值变量和地址变量,C#也一样,对于string,int,double这些类型的数据,每次改变信息后,都重新申请了存储空间,所以修改同一名称的变量的数据,地址也发生了变化,所以可以看见lstStr[0]和lstStr[1]的数据是一样的;反之对于List<string[]>来说,string[]和类来说声明了一个变量,其实变量指向的是地址,就算改变信息变量指向的地址是不会改变的,对于同一变量改变了数据,其实lstArray[0]和lstArray[1]说指向的数据地址是同一个,当然数据都一样。

newCode:

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CnBog20140824
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string[] array = new string[1];
            array[0] = "张三";
            List<string[]> lstArray = new List<string[]>();
            lstArray.Add(array);
            array = new string[1];
            array[0] = "李四";
            lstArray.Add(array);

            Console.ReadKey();
        }
    }
}
View Code

      输出结果: 每次使用的时候重新new 空间,那么lstArray里面数据就不一样了

bubuko.com,布布扣

 

 

C#基础之集合1

标签:style   blog   http   color   os   使用   io   数据   ar   

原文地址:http://www.cnblogs.com/FourLeafCloverZc/p/3933574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!