为什么比较每个 C# 字典 Key/Value 对给出不同的结果,而不是一次完成比较字典键和值?
Why does comparing each of C# Dictionary Key/Value pair gives different result, than comparing Dictionary Keys and Values done at once?
我目前不得不将一些数据放入字典中,以检查一些实际数据是否与我的一些测试的预期数据相匹配。
为了这个任务,我创建了一个看起来像这样的字典:
Dictionary<string, string> dict = new Dictionary<string, string>(){
{a, a},
{b, b},
{c, c}
};
我首先尝试比较条件语句中的字典值和键,如下所示,我对这个条件语句的错误结果感到有点惊讶:
if(dict.Keys.Equals(dict.Values)) {
///// received false as a result here //////
}
然后,当我尝试下一个方法,即遍历所有字典项并比较它们的每个值键对时,它突然给我所有的预期(真实)结果词典条目:
foreach (var item in dict) {
if (item.Key.Equals(item.Value))
{
///// received true as a result /////
}
else { other code here }
}
为什么我得到的第一种方法的结果是错误的?
如果您查看 docs.
,您认为它们都是 ICollection
查字典 reference source class。
Keys
和 Values
属性是使用不同的集合类型实现的。
// Line 135
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
// Line 157
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
此外,如果您查看 KeyCollection
和 ValueCollection
类,您会注意到 Equals()
方法没有其他实现。由于那些 class 不是从任何其他 class 派生的,您可以确定 dict.Keys.Equals(dict.Values)
将调用 object.Equals()
Method.
这个调用显然会return false。
我目前不得不将一些数据放入字典中,以检查一些实际数据是否与我的一些测试的预期数据相匹配。
为了这个任务,我创建了一个看起来像这样的字典:
Dictionary<string, string> dict = new Dictionary<string, string>(){
{a, a},
{b, b},
{c, c}
};
我首先尝试比较条件语句中的字典值和键,如下所示,我对这个条件语句的错误结果感到有点惊讶:
if(dict.Keys.Equals(dict.Values)) { ///// received false as a result here ////// }
然后,当我尝试下一个方法,即遍历所有字典项并比较它们的每个值键对时,它突然给我所有的预期(真实)结果词典条目:
foreach (var item in dict) { if (item.Key.Equals(item.Value)) { ///// received true as a result ///// } else { other code here } }
为什么我得到的第一种方法的结果是错误的?
如果您查看 docs.
,您认为它们都是ICollection
查字典 reference source class。
Keys
和 Values
属性是使用不同的集合类型实现的。
// Line 135
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
// Line 157
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
此外,如果您查看 KeyCollection
和 ValueCollection
类,您会注意到 Equals()
方法没有其他实现。由于那些 class 不是从任何其他 class 派生的,您可以确定 dict.Keys.Equals(dict.Values)
将调用 object.Equals()
Method.
这个调用显然会return false。