茶叶网站开发目的和意义,桂林网站建设制作,建网站需要准备什么,西安优化seo本文内容
隐式数值转换显式数值转换
C# 提供了一组整型和浮点数值类型。 任何两种数值类型之间都可以进行隐式或显式转换。 必须使用强制转换表达式来执行显式转换。
1、隐式数值转换
下表显示内置数值类型之间的预定义隐式转换#xff1a;
From到sbyteshort、int、long、…本文内容
隐式数值转换显式数值转换
C# 提供了一组整型和浮点数值类型。 任何两种数值类型之间都可以进行隐式或显式转换。 必须使用强制转换表达式来执行显式转换。
1、隐式数值转换
下表显示内置数值类型之间的预定义隐式转换
From到sbyteshort、int、long、float、double、decimal 或 nint。byteshort、ushort、int、uint、long、ulong、float、double、decimal、nint 或 nuintshortint、long、float、double、decimal 或 nintushortint、uint、long、ulong、float、double、decimal、nint 或 nuintintlong、float、double、decimal 或 nintuintlong、ulong、float、double、decimal 或 nuintlongfloat、double 或 decimalulongfloat、double 或 decimalfloatdoublenintlong、float、double 或 decimalnuintulong、float、double 或 decimal
从 int、uint、long、ulong、nint 或 nuint 到 float 的隐式转换以及从 long、ulong、nint 或 nuint 到 double 的隐式转换可能会丢失精准率但绝不会丢失一个数量级。 其他隐式数值转换不会丢失任何信息。
注意 任何整型数值类型都可以隐式转换为任何浮点数值类型。 不存在针对 byte 和 sbyte 类型的隐式转换。 不存在从 double 和 decimal 类型的隐式转换。 decimal 类型和 float 或 double 类型之间不存在隐式转换。 类型 int 的常量表达式的值例如由整数文本所表示的值如果在目标类型的范围内则可隐式转换为 sbyte、byte、short、ushort、uint、ulong、nint 或 nuint byte a 13;
byte b 300; // CS0031: Constant value 300 cannot be converted to a byte如前面的示例所示如果该常量值不在目标类型的范围内则发生编译器错误 CS0031。
2、显式数值转换
下表显示不存在隐式转换的内置数值类型之间的预定义显式转换
From到sbytebyte、ushort、uint、ulong 或 nuintbytesbyteshortsbyte、byte、ushort、uint、ulong 或 nuintushortsbyte、byte 或 shortintsbyte、byte、short、ushort、uint、ulong 或 nuint。uintsbyte、byte、short、ushort、int 或 nintlongsbyte、byte、short、ushort、int、uint、ulong、nint 或 nuintulongsbyte、byte、short、ushort、int、uint、long、nint 或 nuintfloatsbyte、byte、short、ushort、int、uint、long、ulong、decimal、nint 或 nuintdoublesbyte、byte、short、ushort、int、uint、long、ulong、float、decimal、nint 或 nuintdecimalsbyte、byte、short、ushort、int、uint、long、ulong、float、double、nint 或 nuintnintsbyte、byte、short、ushort、int、uint、ulong 或 nuintnuintsbyte、byte、short、ushort、int、uint、long 或 nint
显式数值转换可能会导致数据丢失或引发异常通常为 OverflowException。
注意 将整数类型的值转换为另一个整数类型时结果取决于溢出检查上下文。 在已检查的上下文中如果源值在目标类型的范围内则转换成功。 否则会引发 OverflowException。 在未检查的上下文中转换始终成功并按如下方式进行 如果源类型大于目标类型则通过放弃其“额外”最高有效位来截断源值。 结果会被视为目标类型的值。 如果源类型小于目标类型则源值是符号扩展或零扩展以使其与目标类型的大小相同。 如果源类型带符号则是符号扩展如果源类型是无符号的则是零扩展。 结果会被视为目标类型的值。 如果源类型与目标类型的大小相同则源值将被视为目标类型的值。 将 decimal 值转换为整型类型时此值会向零舍入到最接近的整数值。 如果生成的整数值处于目标类型的范围之外则会引发 OverflowException。 将 double 或 float 值转换为整型类型时此值会向零舍入到最接近的整数值。 如果生成的整数值处于目标类型范围之外则结果会取决于溢出上下文。 在已检查的上下文中引发 OverflowException而在未检查的上下文中结果是目标类型的未指定值。 将 double 转换为 float 时double 值舍入为最接近的 float 值。 如果 double 值太小或太大无法匹配 float 类型结果将为零或无穷大。 将 float 或 double 转换为 decimal 时源值转换为 decimal 表示形式并并五入到第 28 位小数后最接近的数如有必要。 根据源值的值可能出现以下结果之一 如果源值太小无法表示为 decimal结果则为零。 如果源值为 NaN非数值、无穷大或太大而无法表示为 decimal则引发 OverflowException。 将 decimal 转换为 float 或 double 时源值分别舍入为最接近的 float 或 double 值。