简体   繁体   English

C#int不包含Clone的定义

[英]C# int does not contain a definition for Clone

I have a Dictionary that I need to copy, since it is not possible to change a Dictionary in a foreach loop. 我有一个我需要复制的字典,因为不可能在foreach循环中更改字典。 (Will lead to the error "Collection was modified; enumeration operation may not execute") After I learned (将导致错误“集合被修改;枚举操作可能无法执行”)

dictTemp.Add(dict);

will just reference one Dictionary to another. 只会将一个字典引用到另一个字典。 I tried to copy it 我试图复制它

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

But I sill got the error and so I think the Add of the Key and the Value is just a reference. 但是我仍然犯错,所以我认为键和值的加法只是一个参考。 I looked about the problem and found a solution by deep copy with Clone (.Net 2.0). 我研究了这个问题,并通过Clone(.Net 2.0)进行了深度复制,找到了解决方案。 https://stackoverflow.com/a/139841/3772108 https://stackoverflow.com/a/139841/3772108

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value.Clone());
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

But it is not possible in .Net 4.5 because of the message "'int' does not contain a definition for Clone and no extension method Clone accepting a first argument of type 'int' could be found" 但是在.Net 4.5中是不可能的,因为消息“'int'不包含Clone的定义,也找不到扩展方法Clone接受类型为'int'的第一个参数”

Now is my question in the year 2017, how is it possible to COPY a dictionary completely. 现在是我在2017年的问题,怎么可能完全复制字典。 (Not referencing it) Or is there a smarter/better way? (不引用它)还是有一种更聪明/更好的方法?

First, you try to clone an int not the dictionary. 首先,您尝试克隆一个int而不是字典。 You don't need to clone value types, just assign them to the variable and you get a "clone". 您不需要克隆值类型,只需将它们分配给变量即可获得“克隆”。

Your foreach -loop has also a bug, you check if !dict.ContainsKey instead of !dictTemp.ContainsKey : 您的foreach循环也有一个错误,您检查是否是!dict.ContainsKey而不是!dictTemp.ContainsKey

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dictTemp.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

Finally, you can use the constructor to get a "clone": 最后,您可以使用构造函数获取“克隆”:

var dictTemp = new Dictionary<string, int>(dict);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM