如果您的意思是您必须重复执行此操作,并且它又长又丑,请将逻辑抽象到另一个类并使用扩展方法。
public static class DictionaryExtensions
{
public static DictionaryChecker<TKey,TValue> contains<TKey,TValue>(this IDictionary<TKey,TValue> dictionary, TValue value)
{
return new DictionaryChecker<TKey,TValue>(value, dictionary);
}
}
public class DictionaryChecker<TKey,TValue>
{
TValue value;
IDictionary<TKey,TValue> dictionary;
internal DictionaryChecker(TValue value, IDictionary<TKey, TValue> dictionary)
{
this.value = value;
this.dictionary = dictionary;
}
public bool For(TKey key)
{
TValue result;
return dictionary.TryGetValue(key, out result) && result.Equals(value);
}
}
现在将您的代码替换为:
if(!someDictionary.contains(actual).For(id)){
// id not known yet or associated value changed.
}