【问题标题】:Dictionary<> is reporting invalid key when it's not字典<> 报告无效键时它不是
【发布时间】:2010-12-03 20:17:02
【问题描述】:

我有一些代码在索引 0 处将 Func&lt;short&gt; 添加到 Dictionary&lt;byte, Func&lt;short&gt;&gt;。稍后,包含字典的类中的一些代码尝试提取此 Func(通过 TryGetValue)并执行它,引发异常如果它不起作用。即使被访问的索引是有效的,它也会抛出表示函数提取失败的异常。为什么是这样? (如有需要可提供代码)

    //processor construction and setup
    VirtualProcessor processor = new VirtualProcessor();
    ...
    processor.InputChannels.Add(0, () => { return 2; });//the func i'm trying to access
    //end processor construction and setup
    //build program
    Dictionary<short, Command> commands = new Dictionary<short, Command>();
    commands.Add(0, CommandFactory.CreateInputCommand(0, 0));//this, in a roundabout way, attempts to call the func
    commands.Add(1, CommandFactory.CreateLoadCommand(1, 200));
    commands.Add(2, CommandFactory.CreateAddCommand(0, 1, 2));
    commands.Add(3, CommandFactory.CreateHaltCommand());
    //end build program
    //execution
    processor.CurrentProgram = commands;
    processor.ExecuteTillHalt();
    //end execution
    Console.ReadLine();

在开关盒沙漠中的某个地方,在另一个类中......

    Func<short> inChannel;
    InputChannels.TryGetValue(command.Data2, out inChannel);//the attempt to access the func, this is the second value supplied to CreateInputCommand above
    if (inChannel != null)
            Registers[command.Data1] = inChannel();//should be here
    else
            throw new InvalidInputChannelException("Invalid input channel " + command.Data2); //throws this

【问题讨论】:

  • 您需要提供您的代码,这样我们才能看到实际发生了什么。
  • 是的,请务必显示重现问题的最小代码,仅从口头描述中无法调试它。

标签: .net exception dictionary key


【解决方案1】:

可能是您的代码中的一个错误 - 为什么要使用 TryGetValue,然后检查该值是否为 null?我会将其重写为:

if (InputChannels.TryGetValue(command.Data2, out inChannel))
    Registers[command.Data1] = inChannel();
else
    throw ...

如果其中一个函数返回 null,您将得到您所描述的结果。

【讨论】:

  • 将其移入 if 语句时仍然失败。
【解决方案2】:

确保您对CommandFactory.CreateInputCommand 的调用永远不会返回null。特别是,您的代码建议它为以下调用返回 null

CommandFactory.CreateInputCommand(0, 0)

【讨论】:

  • 我真的想通了。我忘记了我在属性分配器中进行了调用,该调用清除了该类的所有设置。我现在修好了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 2019-05-15
  • 2021-09-12
相关资源
最近更新 更多