如何将一个Dictionary<string, string>
复制到另一个new Dictionary<string, string>
,使它们不是同一个object?
发布于 2011-05-11 19:00:33
假设您希望它们是单独的对象,而不是对同一对象的引用将源字典传递到destination's constructor中
Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = new Dictionary<string, string>(d);
“因此它们不是同一个对象。”
歧义比比皆是--如果你真的想让它们成为对同一对象的引用:
Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = d;
(在上述内容之后更改d
或d2
都会影响两者)
发布于 2011-05-11 19:04:52
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"]);
}
}
发布于 2020-08-13 15:45:43
阿迈勒答案的一行版本:
var second = first.Keys.ToDictionary(_ => _, _ => first[_]);
https://stackoverflow.com/questions/5963115
复制相似问题