【问题标题】:System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary; exception getting in c#System.Collections.Generic.KeyNotFoundException:给定的键不在字典中;在c#中出现异常
【发布时间】:2016-02-15 15:13:51
【问题描述】:

我有一本字典正在动态地从字典中获取你的值,但有时它会给出异常。有人可以帮忙吗

如何在字典中执行某些操作之前检查 test[typeof(T)].Key.ColumnName 的值。

如果我使用 !string.isnullorEmpty ,它本身就会抛出错误。 代码

 int ID=123;
 private Dictionary<Type, DataTableAttribute> test
 parameters.AddInt32Parameter(test[typeof(T)].Key.ColumnName, ID);

-- 谢谢

【问题讨论】:

  • 你的问题是什么,是“如果键不存在,我如何尝试从字典中检索值并优雅地处理”或“为什么字典中不存在键”或者“这个异常到底意味着什么”?
  • 此外:您提供的帖子根本无法编译,因此不会抛出任何异常。

标签: c# asp.net dictionary


【解决方案1】:

您可以使用ContainsKey 来避免异常

int ID=123;
Dictionary<Type, DataTableAttribute> test

// fill test-dictionary

if (test.ContainsKey(typeof(T)) 
{
    parameters.AddInt32Parameter(test[typeof(T)].Key.ColumnName, ID);
}

或者使用TryGetValue:

DataTableAttribute attr;
if (test.TryGetValue(typeof(T), out attr) 
{
    // ...
}

【讨论】:

  • 也可以使用TryGetValue
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多