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

后端 未结 7 1863
谎友^
谎友^ 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:53

    Because there will not be any implicit conversion between Nonliteral type to larger sized short.

    Implicit conversion is only possible for constant-expression.

    public static void Write(short v) { }
    

    Where as you are passing integer value as an argument to short

    int i=1;
    Write(i);  //Which is Nonliteral here
    

提交回复
热议问题