Why does “int[] is uint[] == true” in C#

前端 未结 5 1141
死守一世寂寞
死守一世寂寞 2020-11-27 05:12

Can somebody clarify the C# is keyword please. In particular these 2 questions:

Q1) line 5; Why does this return true?

Q2) line 7; Why no cast e

5条回答
  •  不知归路
    2020-11-27 06:02

    C# and the CLR have somewhat different conversion rules.

    You can't directly cast between int[] and uint[] in C# because the language doesn't believe any conversion is available. However, if you go via object the result is up to the CLI. From the CLI spec section 8.7 (I hope - I'm quoting an email exchange I had on this topic with Eric Lippert a while ago):

    Signed and unsigned integral primitive types can be assigned to each other; e.g., int8 := uint8 is valid. For this purpose, bool shall be considered compatible with uint8 and vice versa, which makes bool := uint8 valid, and vice versa. This is also true for arrays of signed and unsigned integral primitive types of the same size; e.g., int32[] := uint32[] is valid.

    (I haven't checked, but I assume that this sort of reference type conversion being valid is what makes is return true as well.)

    It's somewhat unfortunate that there are disconnects between the language and the underlying execution engine, but it's pretty much unavoidable in the long run, I suspect. There are a few other cases like this, but the good news is that they rarely seem to cause significant harm.

    EDIT: As Marc deleted his answer, I've linked to the full mail from Eric, as posted to the C# newsgroup.

提交回复
热议问题