gpt4 book ai didi

c# - 制作字典的深拷贝

转载 作者:行者123 更新时间:2023-11-30 20:23:42 26 4
gpt4 key购买 nike

我有一个名为 baseDictionary 的字典。键是一个字符串,值是名为 myData 的类的属性。特别是这些属性是:“年龄”(作为整数)、“国籍”(作为字符串)和“收入”(作为 double )。

所以 baseDictionary 有一些字符串作为键,每个键都有一系列与特定人相关的属性。我想在某个时候制作这本词典的深拷贝,这样我就可以在不修改原始词典内容的情况下使用这个新副本。我在 stackoverflow 中找到了一个答案,建议使用以下代码来执行此深拷贝:

public static Dictionary<TKey, TValue>
CloneDictionaryCloningValues<TKey, TValue>(
Dictionary<TKey, TValue> original) where TValue : ICloneable
{
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(
original.Count, original.Comparer);

foreach (KeyValuePair<TKey, TValue> entry in original)
{
ret.Add(entry.Key, (TValue) entry.Value.Clone());
}
return ret;
}

问题是我无法理解应该如何修改它以使其与我的词典一起使用。例如我试过:

public static Dictionary<string, myData> CloneDictionaryCloningValues<TKey, TValue>
(Dictionary<string, myData> original) where TValue : ICloneable
{
Dictionary<string, myData> ret = new Dictionary<string, myData>(original.Count,
original.Comparer);
foreach (KeyValuePair<string, myData> entry in original)
{
ret.Add(entry.Key, (myData)entry.Value.Clone());
}
return ret;
}

但是我收到以下错误并且不起作用。

Error 3 'Project2.myData does not contain a definition for 'Clone' and no extension method 'Clone' accepting a first argument of type 'Project2.myDatacould be found (are you missing a using directive or an assembly reference?)

我该如何解决这个问题?

最佳答案

如果让 myData 类实现 ICloneable 接口(interface),则根本不需要更改 CloneDictionaryCloningValues 方法:

public class myData : ICloneable {

// your code

public object Clone() {
// whatever you need to create a copy, for example:
return new myData() {
age = this.age,
nationality = this.nationality,
income = this.income
};
}

}

您还可以重写/重载方法以采用克隆方法,而不是要求 IClonable 接口(interface):

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
(Dictionary<TKey, TValue> original, Func<TValue, TValue> clone)
{
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer);
foreach (KeyValuePair<TKey, TValue> entry in original) {
ret.Add(entry.Key, clone(Value));
}
return ret;
}

然后您使用创建项目副本的函数调用该方法:

myCopy = CloneDictionaryCloningValues(myOriginal, item => {
// whatever you need to create a copy, for example:
return new myData() {
age = item.age,
nationality = item.nationality,
income = item.income
};
});

关于c# - 制作字典的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28383150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com