"사용자 정의 사전 래퍼 클래스가 있습니다."- 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.
이것은 매우 합리적인 요구 사항입니다. 빈 사전은 키를 포함해서는 안됩니다. 이은 귀하가 증명해야하는 것입니다.
여기에 다른 방법에 의존 할 수있는 하드 보장이 Count
의 구현 세부 사항 innerDictionary.Count
동일한 것을 약속하는 Contract.Ensures
을 추가하는 샘플 DictionaryWrapper
클래스입니다.IDictionary<TKey, TValue>.TryGetValue
계약을 확인할 수 있도록 ContainsKey
에 비슷한 Contract.Ensures
을 추가합니다.
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();
}
}
출처
2012-02-28 21:28:44
hvd
문제의 근본 원인은이 방법이 모든 키가 발견 될 것이라고 약속하는 것이며 실제로는 제어 할 수 없다는 점입니다. –