2011-05-11 123 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"]); 
    } 
} 
相关问题