sbyte[] can be magically cast to byte[]

后端 未结 1 703
故里飘歌
故里飘歌 2021-02-18 17:17

I\'m not sure whether this is a .NET bug but I find it really interesting.

As expected, I cannot do this:

sbyte[] sbytes = { 1, 2, 3 };
byte[] bytes = sb         


        
1条回答
  •  被撕碎了的回忆
    2021-02-18 17:57

    No, it's not a bug. It's just an impedance mismatch between the C# language rules (which claim there's no conversion available) and the CLR rules (where the conversion is available).

    Note that the compiler really, really thinks it knows best:

    byte[] bytes = new byte[10];
    // error CS0030: Cannot convert type 'byte[]' to 'sbyte[]'
    sbyte[] sbytes = (sbyte[]) bytes; 
    

    And even when you've got code that compiles with a warning, it doesn't really do what it says:

    byte[] bytes = new byte[10];
    // warning CS0184: The given expression is never of the provided ('sbyte[]')
    if (bytes is sbyte[])
    {
        Console.WriteLine("Yes");
    }
    

    Run that code and you don't get output... but if you just change the compile-time type of bytes, it does print Yes:

    object bytes = new byte[10];
    // No warning now
    if (bytes is sbyte[])
    {
        Console.WriteLine("Yes"); // This is reached
    }
    

    0 讨论(0)
提交回复
热议问题