本文介绍了为什么我不能比一个KeyValuePair< TKEY的,TValue>使用默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例外:

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

修改

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

解决方案

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

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

您最好在这种情况下,同性检查的赌注,因为这不是一个结构,你可以控制,是调用默认(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:

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.

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.

这篇关于为什么我不能比一个KeyValuePair&LT; TKEY的,TValue&GT;使用默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 16:19