C#新复制的数组仍保持与源数组的关系
在尝试复制阵列时,我遇到了一个恼人的问题。新数组保留一个关系,即使它是由.copy()方法创建的。情况是这样的, 主类C#新复制的数组仍保持与源数组的关系,c#,arrays,.net,dictionary,C#,Arrays,.net,Dictionary,在尝试复制阵列时,我遇到了一个恼人的问题。新数组保留一个关系,即使它是由.copy()方法创建的。情况是这样的, 主类 Dictionary<string, string>[] DataCurrentDict = new Dictionary<string, string>[result.Data.Count()]; // 1. Here the DataCurrentDict array is filled with values, having DataCurren
Dictionary<string, string>[] DataCurrentDict = new Dictionary<string, string>[result.Data.Count()];
// 1. Here the DataCurrentDict array is filled with values, having DataCurrentDict[0]["Weight"] = "0.345";
ProductData CurrentProductData = new ProductData(DataCurrentDict);
// 2. Here, the CurrentProductData._ProductDataDict[0]["Weight"] = "0.345", GOOD
DataCurrentDict[0]["Weight"] = "1111";
// 3. Here is the problem... After setting a value into DataCurrentDict, the copied array is modified too! So CurrentProductData._ProductDataDict[0]["Weight"] = "1111" ...Why?
Dictionary[]DataCurrentDict=newdictionary[result.Data.Count()];
// 1. 在这里,DataCurrentDict数组被值填充,DataCurrentDict[0][“权重”]=“0.345”;
ProductData CurrentProductData=新产品数据(DataCurrentDict);
// 2. 这里是CurrentProductData.\u ProductDataDict[0][“权重”]=“0.345”,很好
DataCurrentDict[0][“权重”]=“1111”;
// 3. 问题是。。。在DataCurrentDict中设置一个值后,复制的数组也会被修改!那么CurrentProductData._ProductDataDict[0][“权重”]=“1111”…为什么?
ProductData类
public class ProductData : IDisposable
{
private Dictionary<string, string>[] _ProductDataDict;
//CONSTRUCTOR
public ProductData(Dictionary<string, string>[] ProductDataDict)
{
try
{
_ProductDataDict = new Dictionary<string, string>[ProductDataDict.Count()];
Array.Copy(ProductDataDict, _ProductDataDict, ProductDataDict.Length);
}
catch (Exception ex) { }
}
公共类ProductData:IDisposable
{
专用字典[]_ProductDataDict;
//建造师
公共产品数据(字典[]ProductDataDict)
{
尝试
{
_ProductDataDict=新字典[ProductDataDict.Count()];
Copy(ProductDataDict,_ProductDataDict,ProductDataDict.Length);
}
捕获(例外情况除外){}
}
您有一个引用类型的数组,复制引用类型的数组会给您相同的底层引用标识,就这么简单
你可以把引用想象成指向某个东西的地址,比如你橱柜里某个实体的便笺,重新创建便笺不会移动该对象
如果要重新创建引用标识(为对象分配新内存),也就是字典,有几种解决方案
_ProductDataDict = ProductDataDict
.Select(x => x.ToDictionary(y => y.Key, y => y.Value))
.ToArray();
或者(可能更有效)
这是一个从到词典的例外
Dictionary<TKey, TElement> d = new Dictionary<TKey, TElement>(capacity, comparer);
foreach (TSource element in source)
{
d.Add(keySelector(element), elementSelector(element));
}
Dictionary d=新字典(容量、比较器);
foreach(源中的TSource元素)
{
d、 添加(键选择器(元素)、元素选择器(元素));
}
很难知道你想要实现什么,但是你知道引用类型的副本aka reference仍然是相同的引用吗?@00110001,那么如何将内容复制/克隆到一个新的独立数组中呢?我认为.copy()方法用于此,而不是赋值。谢谢
...
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d._count;
Entry[]? entries = d._entries;
for (int i = 0; i < count; i++)
{
if (entries![i].next >= -1)
{
Add(entries[i].key, entries[i].value);
}
}
Dictionary<TKey, TElement> d = new Dictionary<TKey, TElement>(capacity, comparer);
foreach (TSource element in source)
{
d.Add(keySelector(element), elementSelector(element));
}