Why can I pass 1 as a short, but not the int variable i?

后端 未结 7 1857
谎友^
谎友^ 2020-12-07 16:18

Why does the first and second Write work but not the last? Is there a way I can allow all 3 of them and detect if it was 1, (int)1 or i passed in? And really why is one allo

7条回答
  •  攒了一身酷
    2020-12-07 16:58

    There is no implicit conversion from int to short because of the possibility of truncation. However, a constant expression can be treated as being of the target type by the compiler.

    1? Not a problem: it’s clearly a valid short value. i? Not so much – it could be some value > short.MaxValue for instance, and the compiler cannot check that in the general case.

提交回复
热议问题