Why can't I compare a KeyValuePair with default

后端 未结 6 1909
Happy的楠姐
Happy的楠姐 2020-12-30 19:25

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

if (myString == default(string))

However I g

6条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-30 19:53

    In order you to use the "==" equality operator on any class or struct, it needs to override the operator: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

    KeyValuePair doesn't, and therefore you get the compile error. Note, you'll get the same error if you just try this:

    var k1 = new KeyValuePair();
    var k2 = new KeyValuePair();
    
    bool b = k1 == k2; //compile error
    

    EDIT: As Eric Lippert corrected me in the comments, classes obviously don't need to override the equality operator for "==" to be valid. It'll compile fine and do a reference equality check. My mistake.

提交回复
热议问题