首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 顯式數值轉換完整規則:溢位檢查、精度捨入與例外處理

     編輯:關於C語言

顯式數值轉換(強制轉型)用於不存在隱含轉換的數值型別之間。開發者必須以 (TargetType)value 語法明確表達意圖,並承擔資訊遺失或執行期例外的風險。

完整顯式轉換對照表(來源 → 目標)

來源可顯式轉換的目標型別
sbytebyte, ushort, uint, ulong, char
bytesbyte, char
shortsbyte, byte, ushort, uint, ulong, char
ushortsbyte, byte, short, char
intsbyte, byte, short, ushort, uint, ulong, char
uintsbyte, byte, short, ushort, int, char
longsbyte, byte, short, ushort, int, uint, ulong, char
ulongsbyte, byte, short, ushort, int, uint, long, char
charsbyte, byte, short
floatsbyte, byte, short, ushort, int, uint, long, ulong, char, decimal
doublesbyte, byte, short, ushort, int, uint, long, ulong, char, float, decimal
decimalsbyte, byte, short, ushort, int, uint, long, ulong, char, float, double

執行期轉換規則與例外

  1. 整數 ↔ 整數:checked 內容下溢位拋 OverflowException;unchecked 截斷高位。
  2. 浮點/十進位 → 整數:向最接近整數捨入(MidpointRounding.ToEven);超出範圍拋 OverflowException。
  3. double → float:IEEE 754 捨入;太小變 ±0,太大變 ±∞,NaN 保持 NaN。
  4. 浮點/雙精度 → decimal:轉十進位並捨入至 28 位;太小成 0,太大/∞/NaN 拋 InvalidCastException。
  5. decimal → 浮點/雙精度:捨入至最接近值;可能損失精度但不拋例外。

溢位實測


long max = long.MaxValue; // 9223372036854775807
int i = (int)max;         // 在 unchecked 預設下 → -1
// checked { int j = (int)max; } // 拋 OverflowException

輸出 (int)9223372036854775807 = -1,證明高位被截斷(補數表示)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved