如何才能对象不能比拟为空? [英] How can an object not be compared to null?
问题描述
我有一个方法,是一个KeyValuePair一个'可选'参数。我想传递空的核心方法,此参数的重载,但在核心的方法,当我想检查是否KeyValuePair是空的,我得到以下错误:
I have an 'optional' parameter on a method that is a KeyValuePair. I wanted an overload that passes null to the core method for this parameter, but in the core method, when I want to check if the KeyValuePair is null, I get the following error:
Operator '!=' cannot be applied to operands of type System.Collections.Generic.KeyValuePair<string,object>' and '<null>.
我怎样才能不会被允许检查对象是否为空?
How can I not be allowed to check if an object is null?
推荐答案
KeyValuePair&LT; K,V&GT;
是一个结构,而不是一类。这就像做的:
KeyValuePair<K,V>
is a struct, not a class. It's like doing:
int i = 10;
if (i != null) ...
(虽然这实际上是合法的,有一个警告,由于多为空的转换规则。最重要的一点是,如果
的条件永远是正确的。)
(Although that is actually legal, with a warning, due to odd nullable conversion rules. The important bit is that the if
condition will never be true.)
要使其可选,您可以使用空形式:
To make it "optional", you can use the nullable form:
static void Foo(KeyValuePair<object,string>? pair)
{
if (pair != null)
{
}
// Other code
}
请注意的?在 KeyValuePair&LT;对象,字符串&GT;
这篇关于如何才能对象不能比拟为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!