字典<>如果没有,则报告无效密钥

时间:2009-10-05 04:14:20

标签: .net exception dictionary key

我有一些代码在索引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

2 个答案:

答案 0 :(得分:2)

您的代码中可能存在错误 - 为什么使用TryGetValue,然后检查null值?我会把它重写为:

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

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

答案 1 :(得分:0)

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

CommandFactory.CreateInputCommand(0, 0)