1. ホーム
  2. c#

[解決済み] System.Collections.Generic.KeyNotFoundException: 与えられたキーが辞書に存在しない; c#での例外取得

2022-02-28 03:25:43

質問

私は辞書を持っていて、動的に辞書からe値を取得していますが、何回か例外が発生します。誰かが親切にこの上で助けることができる

ディクショナリーで何らかのアクションを行う前に test[typeof(T)].Key.ColumnName の値をチェックするようにするにはどうすればよいですか。

!string.isnullorEmptyを使用すると、それ自体がエラーを投げます。 コード

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

-- 感謝

解決方法は?

を使用することができます。 キーが含まれる を使用すると、例外を回避することができます。

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) 
{
    // ...
}