17
如何將Dictionary<string, string>
複製到另一個new Dictionary<string, string>
以使它們不是同一個對象?如何將字典的內容複製到C#中的新字典中?
如何將Dictionary<string, string>
複製到另一個new Dictionary<string, string>
以使它們不是同一個對象?如何將字典的內容複製到C#中的新字典中?
假設你的意思是你想他們是單獨的對象,並且對同一個對象不引用:
Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = new Dictionary<string, string>(d);
「使他們不都是同一個對象。」
模糊比比皆是 - 如果你真的想他們是同一個對象的引用:(會影響上述兩個後更改或者d
或d2
)
Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = d;
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"]);
}
}
剛作爲一個側面說明,讓我絆倒一次的東西。如果您使用此方法複製靜態字典,則在副本中所做的更改仍然會影響原始內容 – stuicidle 2017-06-30 10:25:08