「カスタムディクショナリラッパークラスがあります」-を実装しIDictionary<TKey, TValue>
ます。インターフェイスメソッドはコントラクトを指定でき、それらを実装するクラスメソッドはコントラクトを満たす必要があります。この場合、IDictionary<TKey, TValue>.ContainsKey(TKey)
あなたが求めている契約があります:
Contract.Ensures(!Contract.Result<bool>() || this.Count > 0);
論理的には、 (を意味する)!a || b
と読むことができ、それを使用して、これを英語に翻訳することができます。a ===> b
a
b
If ContainsKey() returns true, the dictionary must not be empty.
これは完全に賢明な要件です。空の辞書は、キーが含まれていると主張してはなりません。これはあなたが証明する必要があるものです。
これは、等しいという実装の詳細が他のメソッドが信頼できることを保証するものであることを約束するために追加するサンプルDictionaryWrapper
クラスです。と同様の機能を追加して、契約も検証可能にします。Contract.Ensures
Count
innerDictionary.Count
Contract.Ensures
ContainsKey
IDictionary<TKey, TValue>.TryGetValue
public class DictionaryWrapper<TKey, TValue> : IDictionary<TKey, TValue>
{
IDictionary<TKey, TValue> innerDictionary;
public DictionaryWrapper(IDictionary<TKey, TValue> innerDictionary)
{
Contract.Requires<ArgumentNullException>(innerDictionary != null);
this.innerDictionary = innerDictionary;
}
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(innerDictionary != null);
}
public void Add(TKey key, TValue value)
{
innerDictionary.Add(key, value);
}
public bool ContainsKey(TKey key)
{
Contract.Ensures(Contract.Result<bool>() == innerDictionary.ContainsKey(key));
return innerDictionary.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get
{
return innerDictionary.Keys;
}
}
public bool Remove(TKey key)
{
return innerDictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
return innerDictionary.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get
{
return innerDictionary.Values;
}
}
public TValue this[TKey key]
{
get
{
return innerDictionary[key];
}
set
{
innerDictionary[key] = value;
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
innerDictionary.Add(item);
}
public void Clear()
{
innerDictionary.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return innerDictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
innerDictionary.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() == innerDictionary.Count);
return innerDictionary.Count;
}
}
public bool IsReadOnly
{
get
{
return innerDictionary.IsReadOnly;
}
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return innerDictionary.Remove(item);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return innerDictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return innerDictionary.GetEnumerator();
}
}