2009-10-05 44 views
0

时报告无效密钥我有一些代码在索引0处将一个Func<short>添加到Dictionary<byte, Func<short>>。稍后,包含该字典的类中的某些代码尝试提取此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 
+1

您需要提供你的代码,所以我们可以看到什么是真正* *发生。 –

+1

是的,请确实显示重现问题的最小代码,不可能从这个口头描述中进行调试。 –

回答

2

可能是一个错误 - 为什么要使用TryGetValue,然后检查null值?我会将其改写为:

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

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

+0

将它移入if语句时仍然失败。 – RCIX

0

请确保您致电CommandFactory.CreateInputCommand永不返回null。特别是,你的代码表明,它下面的调用返回null

CommandFactory.CreateInputCommand(0, 0) 
+0

我其实已经想通了。我忘记了我拨打了一个财产分配者的电话,这消除了班级的所有设置。我现在修好了! – RCIX

相关问题