【发布时间】:2014-08-22 19:44:51
【问题描述】:
我创建了一个包含一些项目的类。并从中创建一个字典对象值。 当我在调试模式下查看它时,向字典中添加项目似乎工作正常。 然而,当我尝试检索对象时,我只得到字典中的最后一个对象。但我可以检索所有密钥。 我在这里错过了一些简单的步骤吗?
public class Block
{
public int blockID16 { get; set; }
public int blockID {get; set;}
public string blockName {get; set;}
public int instance {get;set;}
}
// init object and dictionary
Block block = new Block();
Dictionary<int, Block> blockDict = new Dictionary<int, Block>();
// read an xml file and write to the dictionary
blockDict.Add(block.blockID16, block);
// I then return the dictionary from a called method below and read it.
Dictionary<int, Block> blockDict = new Dictionary<int, Block>();
blockDict = XMLreader.Reader();
Block block1 = new Block();
foreach(KeyValuePair<int, Block> entry in blockDict)
{
block1.blockID16 = entry.Value.blockID16;
block1.blockName=entry.Value.blockName;
block1.instance = entry.Value.instance;
block1.blockID = entry.Value.blockID;
keyValue = entry.Key;
}
【问题讨论】:
-
在循环中创建您的
Block。您正在使用它的相同实例。 -
看看将你的块添加到字典中的代码的细节会很有趣
-
block除了设置它的值之外,你最终会做什么? -
你想做什么?假设循环有效,您所做的只是循环并将其分配给 block1,但您实际上并没有对它做任何事情。
-
哥们,你错过了 foreach 中的 Add 方法吗?哈哈
标签: c# object dictionary