如何将对象与null进行比较?

Pro*_*ofK 47 .net c# generics

我在一个KeyValuePair方法上有一个'可选'参数.我想要一个将null传递给此参数的核心方法的重载,但是在核心方法中,当我想检查KeyValuePair是否为null时,我收到以下错误:

Operator '!=' cannot be applied to operands of type System.Collections.Generic.KeyValuePair<string,object>' and '<null>. 
Run Code Online (Sandbox Code Playgroud)

如何禁止检查对象是否为空?

Jon*_*eet 80

KeyValuePair<K,V>是一个结构,而不是一个类.这就像做:

int i = 10;
if (i != null) ...
Run Code Online (Sandbox Code Playgroud)

(虽然这实际上是合法的,带有警告,由于奇怪的可空转换规则.重要的是if条件永远不会成立.)

要使其"可选",您可以使用可以为空的形式:

static void Foo(KeyValuePair<object,string>? pair)
{
    if (pair != null)
    {
    }
    // Other code
}
Run Code Online (Sandbox Code Playgroud)

注意?在KeyValuePair<object,string>?

  • "(i!= null)"确实会生成一个警告,但遗憾的是,对于根据MSDN指南重载Equals/== /!=的用户定义值类型,没有这样的警告.当我实现"struct Foo"并且我的客户端期望"if(someFoo!= null)"是检查someFoo是否有值的合理方法时非常混乱.:-P (4认同)

eud*_*mos 13

我正在回答这个问题,尽管它的年龄很大,因为它是"测试keyvaluepair为null"的第一个Google结果

指定的答案是正确的,但它并没有完全回答问题,至少我所拥有的那个,我需要测试它的存在,KeyValuePair并继续检查Dictionary它是否不存在我的方式我期待着.

使用上面的方法对我来说不起作用,因为编译器在获取KeyValuePair.Value时会窒息KeyValuePair<>?,所以最好使用default(KeyValuePair<>)这个问题+答案中看到的.KeyValuePair的默认值


Ant*_*nes 6

因为KeyValuePair是结构(值类型),所以只能比较引用类型上的空值.

我猜你还没写过额外的超载.当您尝试将null作为KeyValuePair的值传递时,它将失败.