隐式数值转换表(C# 参考)Implicit numeric conversions table (C# Reference)

下表显示 .NET 数值类型之间的预定义隐式转换。The following table shows the predefined implicit conversions between .NET numeric types.

FromFrom To
sbytesbyte shortintlongfloatdoubledecimalshort, int, long, float, double, or decimal
bytebyte shortushortintuintlongulongfloatdoubledecimalshort, ushort, int, uint, long, ulong, float, double, or decimal
charchar ushortintuintlongulongfloatdoubledecimalushort, int, uint, long, ulong, float, double, or decimal
shortshort intlongfloatdoubledecimalint, long, float, double, or decimal
ushortushort intuintlongulongfloatdoubledecimalint, uint, long, ulong, float, double, or decimal
intint longfloatdoubledecimallong, float, double, or decimal
uintuint longulongfloatdoubledecimallong, ulong, float, double, or decimal
longlong floatdoubledecimalfloat, double, or decimal
ulongulong floatdoubledecimalfloat, double, or decimal
floatfloat double

备注Remarks

  • 任何整型类型都可以隐式转换为任何浮点类型Any integral type is implicitly convertible to any floating-point type.

  • 在从 intuintlongulong 转换为 float,以及从 longulong 转换为 double 时,可能会丢失精度,但不会丢失量值。Precision but not magnitude might be lost in the conversions from int, uint, long, or ulong to float and from long or ulong to double.

  • 不存在针对 charbytesbyte 类型的隐式转换。There are no implicit conversions to the char, byte, and sbyte types.

  • 不存在从 doubledecimal 类型的隐式转换。There are no implicit conversions from the double and decimal types.

  • decimal 类型和 floatdouble 类型之间不存在隐式转换。There are no implicit conversions between the decimal type and the float or double types.

  • 类型 int 的常量表达式的值(例如,由整数型字面量表示的值)可以转换为 sbytebyteshortushortuintulong,前提是它在目标类型的范围内:A value of a constant expression of type int (for example, a value represented by an integral literal) can be converted to sbyte, byte, short, ushort, uint, or ulong, provided it's within the range of the destination type:

    byte a = 13;    // Compiles
    byte b = 300;   // CS0031: Constant value '300' cannot be converted to a 'byte'
    

有关隐式转换的详细信息,请参阅 C# 语言规范隐式转换章节。For more information about implicit conversions, see the Implicit conversions section of the C# language specification.

请参阅See also