【问题标题】:Why does this code only return the last object from the dictionary?为什么这段代码只返回字典中的最后一个对象?
【发布时间】: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


【解决方案1】:

是的,克里斯,我确实一遍又一遍地使用该对象而没有重新实例化它。谢谢,我仍在学习并且只编程了几周,并且将对象引用与变量值混淆了。现在工作正常。这只是一个测试,帮助我在转向更大的项目之前了解如何将对象添加到字典中。谢谢大家。

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多