&引用;字典嵌套“;在C#中?
我是C#的初学者,我正在努力做到以下几点: 我创建了一个字典:&引用;字典嵌套“;在C#中?,c#,C#,我是C#的初学者,我正在努力做到以下几点: 我创建了一个字典:\u innerProducts=new Dictionary() 然后再创建一个字典来存储第一个字典:\u KitProducts=new dictionary() 第一个(innerProducts)包含我从and.xml文件收集的大约15个产品属性,TKey是产品代码 在收取所有房东费用后,我打电话: _KitProducts.Add(_innerProducts["cProd"], _innerProducts); 当我通过
\u innerProducts=new Dictionary()代码>
然后再创建一个字典来存储第一个字典:\u KitProducts=new dictionary()代码>
第一个(innerProducts
)包含我从and.xml文件收集的大约15个产品属性,TKey是产品代码
在收取所有房东费用后,我打电话:
_KitProducts.Add(_innerProducts["cProd"], _innerProducts);
当我通过调试观看时,它运行良好,正如我所看到的:
问题是,我无法使用与第一个\u innerProducts
“cProd”相同的TKey添加另一组心房,因此在foreach中我放置了一个\u innerProducts.Clear()代码>在末尾
问题是当我清除它时,它不仅清除了当前的内部产品,还清除了产品的价值:
我不确定这是否是因为我读过的那些“按参考”而不是“按价值”的讲座(记得我刚刚开始),那么在这种情况下我应该怎么做
这将是很多这样的情况,我知道我需要存储它(但我仍然没有学习实体框架,正在研究它),而我只是为了学习而存储在字典中
感谢并抱歉,英语不是我的主要语言。将值添加到外部词典后,\u innerProducts
和外部词典条目的值都指向同一个对象:
+-----------------------+
| your inner dictionary |
+-----------------------+
^ ^
| |
_innerProducts value in the outer dictionary entry
执行\u innerProducts.Clear()
时,将清空该字典,结果如下:
+-----------------------+
| empty dictionary |
+-----------------------+
^ ^
| |
_innerProducts value in the outer dictionary entry
因此,与其清空现有实例,不如创建一个新实例,即replace
_innerProducts.Clear(); // "a.DoSomething()" operates on the object referenced by a
与
这样,您就不会修改现有的内部字典,而是让变量\u innerProducts
指向一个新的字典
如果可能,更简单更好:将\u innerProducts
的声明移动到用于填充\u KitProducts
的循环中。这将确保每个循环迭代都有自己的内部字典实例。如果您希望避免在主字典中更改数据,只需将内部字典的副本放入即可
var key = _innerProducts["cProd"];
var value = new Dictionary<string, string>(_innerProducts);
_KitProducts.Add(key, value);
var key=_innerProducts[“cProd”];
var值=新字典(_innerProducts);
_KitProducts.Add(关键、价值);
你能分享你用来做这件事的代码吗(如问题中的代码)。在参数传递方面,这不是“按值”对“按引用”,而是因为字典中有对值的引用。我建议你读一读这本书,我不太清楚你想达到什么目的,但了解C#在对象和引用方面的工作方式非常重要。感谢你如此详细地解释,所以我不仅解决了问题(将.clear()更改为新字典),而且还理解了为什么会发生这种情况!
+-----------------------+ +-----------------------+
| a new, empty dict. | | your inner dictionary |
+-----------------------+ +-----------------------+
^ ^
| |
_innerProducts value in the outer dictionary entry
var key = _innerProducts["cProd"];
var value = new Dictionary<string, string>(_innerProducts);
_KitProducts.Add(key, value);