基本的に、コードコントラクトを使用して、キーがConcurrentDictionaryに存在するかどうかを判断することが、コードコントラクトの許容可能な使用法であるかどうかを知りたいです。実行時の辞書の状態に依存するため、パラメータチェック以上のものであるため、私には正しく感じられません。
public class MyClass
{
private ConcurrentDictionary<string, object> someItems =
new ConcurrentDictionary<string, object>();
public object GetItem(string itemName)
{
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(itemName));
// ?? Is this a correct alternative to checking for null???
Contract.Requires<KeyNotFoundException>(someItems.ContainsKey(itemName));
return someItems[itemName];
}
}
しかし、それが問題ない場合は、以下の従来の方法に比べて、2つのContract.Requiresと1つのリターンを持つよりクリーンな方法です。
public class MyClass
{
private ConcurrentDictionary<string, object> someItems =
new ConcurrentDictionary<string, object>();
public object GetItem(string itemName)
{
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(itemName));
// Traditional null check
var item = someItems[itemName];
if (item == null)
{
throw new KeyNotFoundException("Item " + itemName + " not found.");
}
return item;
}
}