2011-05-11 117 views

回答

51

假設你的意思是你想他們是單獨的對象,並且對同一個對象不引用:

Dictionary<string, string> d = new Dictionary<string, string>(); 
Dictionary<string, string> d2 = new Dictionary<string, string>(d); 

「使他們不都是同一個對象。」

模糊比比皆是 - 如果你真的想他們是同一個對象的引用:(會影響上述兩個後更改或者dd2

Dictionary<string, string> d = new Dictionary<string, string>(); 
Dictionary<string, string> d2 = d; 

+1

剛作爲一個側面說明,讓我絆倒一次的東西。如果您使用此方法複製靜態字典,則在副本中所做的更改仍然會影響原始內容 – stuicidle 2017-06-30 10:25:08

5
using System; 
using System.Collections.Generic; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Dictionary<string, string> first = new Dictionary<string, string>() 
     { 
      {"1", "One"}, 
      {"2", "Two"}, 
      {"3", "Three"}, 
      {"4", "Four"}, 
      {"5", "Five"}, 
      {"6", "Six"}, 
      {"7", "Seven"}, 
      {"8", "Eight"}, 
      {"9", "Nine"}, 
      {"0", "Zero"} 
     }; 

     Dictionary<string, string> second = new Dictionary<string, string>(); 
     foreach (string key in first.Keys) 
     { 
      second.Add(key, first[key]); 
     } 

     first["1"] = "newone"; 
     Console.WriteLine(second["1"]); 
    } 
} 
相關問題