Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c# - How can an object not be compared to null?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

Note the ? in KeyValuePair<object,string>?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...