如何将字典内容复制到C#中的新字典?

如何将Dictionary复制到另一个new Dictionary以便它们不是同一个对象?

假设您的意思是希望它们是单个对象,而不是对同一对象的引用:

 Dictionary d = new Dictionary(); Dictionary d2 = new Dictionary(d); 

“所以他们不是同一个对象。”

歧义比比皆是 – 如果你确实希望它们是对同一个对象的引用:

 Dictionary d = new Dictionary(); Dictionary d2 = d; 

(在上述之后更改dd2将影响两者)

 using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Dictionary first = new Dictionary() { {"1", "One"}, {"2", "Two"}, {"3", "Three"}, {"4", "Four"}, {"5", "Five"}, {"6", "Six"}, {"7", "Seven"}, {"8", "Eight"}, {"9", "Nine"}, {"0", "Zero"} }; Dictionary second = new Dictionary(); foreach (string key in first.Keys) { second.Add(key, first[key]); } first["1"] = "newone"; Console.WriteLine(second["1"]); } }