为什么我不能比一个KeyValuePair< TKEY的,TValue>使用默认LT、KeyValuePair、TKEY、GT

2023-09-03 11:53:02 作者:青黛色

在净2.5我通常可以得到一个价值,它的类型默认

之间的相等比较(==)

 如果(MyString的==默认(字符串))
 

不过,我当我尝试运行在默认的相等比较得到下面的异常KeyValuePair和KeyValuePair

code样品(从pre-扩展方法,原拉姆达静态ListUtilities类:))

 公共静态TKEY的
        FirstKeyOrDefault< TKEY的,TValue>(词典< TKEY的,TValue>查找,
                   predicate< KeyValuePair< TKEY的,TValue>> predicate)
{
    KeyValuePair< TKEY的,TValue>对= FirstOrDefault(查找,predicate);

    回归对==默认(KeyValuePair< TKEY的,TValue>)?
                   默认(TKEY的):pair.Key;
}
 
微服务架构中的key value pair数据结构

例外:

  

算'=='不能被应用到   类型的操作数   System.Collections.Generic.KeyValuePair<字符串,对象>   和   System.Collections.Generic.KeyValuePair<字符串,对象>

是因为,作为一个结构,该KeyValuePair不能为空?如果是这样的话,为什么,因为,presumably,默认情况下实施,以处理不空类型?

修改

有关的记录,我选择了@克里斯汉农作为选择的答案,因为他给了我什么,我一直在寻找,最优雅的选择,和一个简洁的解释,然而,我鼓励阅读@Dasuraga一个非常COM prehensive解释,为什么是这样的话

解决方案

这是因为 KeyValuePair< TKEY的,TValue> 不定义一个定制的==操作符,而不是包括在值类型的predefined列表可以使用它。

下面是一个链接 MSDN文档为该运营商。

  

有关predefined值类型,如果它的操作数的值相等等号(= =)返回true,否则为false。

您最好在这种情况下,同性检查的赌注,因为这不是一个结构,你可以控制,是调用默认(KeyValuePair< TKEY的,TValue>)。等于(对)代替。

In .Net 2.5 I can usually get an equality comparison (==) between a value and its type default

if (myString == default(string))

However I get the following exception when I try to run an equality comparison on a default KeyValuePair and a KeyValuePair

Code Sample (from a pre-extension method, proto-lambda static ListUtilities class :) )

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>'

Is it because, as a struct, the KeyValuePair is not nullable? If this is the case, why, as, presumably, default was implemented to handle not nullable types?

EDIT

For the record, I chose @Chris Hannon as selected answer, as he gave me what I was looking for, the most elegant option, and a succinct explanation, however I do encourage reading @Dasuraga for a very comprehensive explanation as to why this is the case

解决方案

This happens because KeyValuePair<TKey, TValue> does not define a custom == operator and is not included in the predefined list of value types that can use it.

Here is a link to the MSDN documentation for that operator.

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

Your best bet for an equality check in this case, because this is not a struct you have control over, is to call default(KeyValuePair<TKey,TValue>).Equals(pair) instead.