Why can't I implicitly convert a double to an int?

前端 未结 5 1598
暗喜
暗喜 2021-01-19 14:20

You can implicitly convert an int to a double: double x = 5;

You can explicitly convert an int to a double: double x = (double) 5;

<
5条回答
  •  抹茶落季
    2021-01-19 14:32

    C# follows the lead of Java's type system, which ranks types int->long->float->double, and specifies that any type which appears to the left of another may be cast to it. I personally think ranking types in this fashion was a bad idea, since it means that code like long l = getSomeValue(); float f=l; double d=f; will compile cleanly without a squawk despite a severe loss of precision compared with storing l directly to d; it has some other unfortunate consequences as well.

    I suspect Gosling ranked the types as he did in order to ensure that passing a float and a double to a method which is overloaded for (float,float) and (double,double) would use the latter. Unfortunately, his ranking has the unfortunate side-effect that passing an int or long to a method which is only overloaded for float and double will cause the method to use the float overload rather than the double overload.

    C# and .NET follows Java's lead in preferring a long-to-float conversion over a long-to-double; the one thing which "saves" them from some of the consequent method-overloading horrors is that nearly all the .NET Framework methods with overloads for float and double also have an overload for Decimal, and no implicit conversions exist between Decimal and the other floating-point types. As a consequence, attempting to pass a long to a method which has overloads for float, double, and Decimal but not long will result in a compilation error rather than a conversion to float.

    Incidentally, even if the people choosing which implicit conversions to allow had given the issue more thought, it's unlikely that implicit conversions from floating-point types (e.g. double) to discrete types (e.g. int) would have been permitted. Among other things, the best integer representation for the result of a computation that yielded 2.9999999999994 would in some cases be 2, and in other cases it would be 3. In cases where a conversion might sometimes need to be done one way and sometimes another, it's generally good for the language to require that the programmer indicate the actual intention.

提交回复
热议问题