【发布时间】:2011-09-16 19:39:34
【问题描述】:
在 .Net 2.5 中,我通常可以在一个值与其默认类型之间进行相等比较 (==)
if (myString == default(string))
但是,当我尝试对默认 KeyValuePair 和 KeyValuePair 运行相等比较时,出现以下异常
代码示例(来自预扩展方法,proto-lambda 静态 ListUtilities 类:))
public static TKey
FirstKeyOrDefault<TKey, TValue>(Dictionary<TKey, TValue> lookups,
Predicate<KeyValuePair<TKey, TValue>> predicate)
{
KeyValuePair<TKey, TValue> pair = FirstOrDefault(lookups, predicate);
return pair == default(KeyValuePair<TKey, TValue>) ?
default(TKey) : pair.Key;
}
例外:
运算符“==”不能应用于 类型的操作数 'System.Collections.Generic.KeyValuePair
' 和 'System.Collections.Generic.KeyValuePair '
是不是因为 KeyValuePair 作为一个结构体不能为空?如果是这种情况,为什么默认实现了处理不可为空的类型?
编辑
为了记录,我选择@Chris Hannon 作为选择的答案,因为他给了我我想要的东西,最优雅的选择和简洁的解释,但是我鼓励阅读@Dasuraga 以获得非常全面的解释为什么会这样
【问题讨论】:
-
FirstOrDefault
>(查找,谓词)? -
@Jean-Bernard Pellerin,应该从传递的类型推断出来,否则编译器会抱怨。当您将其简化为 myKvp == default(KeyValuePair<...>) 时也会发生异常
-
肯定默认是标量类型? KVP 具有默认值意味着是什么意思?我想你确实在你试图构建的任何上下文中都有一个答案。我怀疑对于非标量,默认值是调用 nil 构造函数所得到的。在这种情况下,我希望对象标识比较返回 false,因为每次调用构造函数时都会得到一个新对象。