程式碼
using System; using System.Collections.Generic; class Program { static void Main() { // // Create and initialize Dictionary. // Dictionary dictionary = new Dictionary(); dictionary.Add("cat", 1); dictionary.Add("dog", 3); dictionary.Add("iguana", 5); // // 複製Dictionary 到第二個物件 // Dictionary copy = new Dictionary(dictionary); // // Change the first Dictionary. It won't change the copy. // dictionary.Add("fish", 4); // // Display the first Dictionary. // Console.WriteLine("--- Dictionary 1 ---"); foreach (var pair in dictionary) { Console.WriteLine(pair); } // // Display the second Dictionary. // Console.WriteLine("--- Dictionary 2 ---"); foreach (var pair in copy) { Console.WriteLine(pair); } } }輸出
--- Dictionary 1 --- [cat, 1] [dog, 3] [iguana, 5] [fish, 4] --- Dictionary 2 --- [cat, 1] [dog, 3] [iguana, 5]摘要
複製整個Dictionary到一個新的Dictionary。Dictionary的類別並沒有定義複製的方法,需使用複製建構式來進行複製。
沒有留言:
張貼留言