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

后端 未结 7 1874
谎友^
谎友^ 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条回答
  •  猫巷女王i
    2020-12-07 16:52

    The compiler has told you why the code fails:

    cannot convert `int' expression to type `short'
    

    So here's the question you should be asking: why does this conversion fail? I googled "c# convert int short" and ended up on the MS C# page for the short keyword:

    http://msdn.microsoft.com/en-us/library/ybs77ex4(v=vs.71).aspx

    As this page says, implicit casts from a bigger data type to short are only allowed for literals. The compiler can tell when a literal is out of range, but not otherwise, so it needs reassurance that you've avoided an out-of-range error in your program logic. That reassurance is provided by a cast.

    Write((short)i)
    

提交回复
热议问题