c# - 为什么我不能将 KeyValuePair<TKey, TValue> 与默认值进行比较

标签 c# .net key-value

在 .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;
}

异常(exception):

Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<string,object>' and 'System.Collections.Generic.KeyValuePair<string,object>'

是因为作为结构,KeyValuePair 不可为空吗?如果是这种情况,为什么要实现 default 来处理不可空类型?

编辑

根据记录,我选择@Chris Hannon 作为选定答案,因为他给了我我正在寻找的东西、最优雅的选项和简洁的解释,但是我鼓励阅读@Dasuraga 以获得非常全面的解释为什么会这样

最佳答案

发生这种情况是因为 KeyValuePair<TKey, TValue>未定义自定义 == 运算符,并且未包含在可以使用它的预定义值类型列表中。

这是 MSDN documentation 的链接对于那个运营商。

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise.

在这种情况下进行相等性检查的最佳方法是调用 default(KeyValuePair<TKey,TValue>).Equals(pair),因为这不是您可以控制的结构。相反。

关于c# - 为什么我不能将 KeyValuePair<TKey, TValue> 与默认值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6379915/

相关文章:

c# - HashSet.IsSuperSetOf 和 IsProperSuperSetOf 之间的区别?

c# - System.Data.OleDb.OleDbException 需要一个或多个参数

c# - 如何获取两个 Point 对象之间的所有点?

c# - 所有 C# .NET 方法的引用库

Redis 增加一个数值 - ERR 值不是整数或超出范围

c# - Process.Start() 导致应用程序挂起

.net - 从 DispatcherObject 继承的类是线程安全的还是线程不安全的?

c# - 如果 StreamWriter 变量在 if 语句内初始化并作为参数传递给 Console.SetOut(),它是否会过早地被 GC 处理?

java - 如何在java中将多级xml扁平化为List<String xpath>?

objective-c - 启用 NSCoder 的类的简单方法