標籤:style blog http color os 使用 io 資料 ar
1.C#中集合用處無處不在,可是對於類似於小編這樣的初學者在初次使用集合會遇到一些小問題.話不多說,看看代碼。
code:
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的每個元素都變成後面被修改的內容了。
原因分析:學過C/C++的都知道,變數分為值變數和地址變數,C#也一樣,對於string,int,double這些類型的資料,每次改變資訊後,都重新申請了儲存空間,所以修改同一名稱的變數的資料,地址也發生了變化,所以可以看見lstStr[0]和lstStr[1]的資料是一樣的;反之對於List<string[]>來說,string[]和類來說聲明了一個變數,其實變數指向的是地址,就算改變資訊變數指向的地址是不會改變的,對於同一變數改變了資料,其實lstArray[0]和lstArray[1]說指向的資料地址是同一個,當然資料都一樣。
newCode:
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裡面資料就不一樣了
C#基礎之集合1