C#基礎之集合1

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.