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

C# 顯式數值轉換完整指南:規則、風險與範例解析

     編輯:關於C#

什麼是顯式數值轉換?

當不存在隱式轉換時,從一種數值類型轉換到另一種數值類型,必須使用顯式轉換(Cast)。這意味著你必須在代碼中明確指示編譯器:「我知道這可能損失精度或拋出例外,但我確定要這麼做。」

所有顯式數值轉換對照表

來源類型目標類型
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。此行為受 checked/unchecked 語境影響。

2. 浮點數轉整數:捨入與溢出

值會捨入至最接近的整數。若超出目標類型範圍,拋出 OverflowException。

3. double 轉 float:精度縮減與特殊值

捨入至最接近的 float。太小變 ±0,太大變 ±無窮大,NaN 保持 NaN。

4. float/double 轉 decimal:28 位精度限制

轉為十進位並捨入至小數點後 28 位。太小變 0,太大或為無窮大/NaN 時拋出 InvalidCastException。

5. decimal 轉 float/double:可能損失精度但不拋例外

捨入至最接近值,可能損失精度,但不會引發例外。

程式範例:溢出導致資訊遺失

using System;
class Test {
    static void Main() {
        long longValue = Int64.MaxValue; // 9223372036854775807
        int intValue = (int)longValue;   // 顯式轉換
        Console.WriteLine("(int){0}={1}", longValue, intValue);
    }
}

輸出結果: (int)9223372036854775807=-1

原因:long 最大值遠超 int 範圍,發生溢出,導致資訊遺失,產生負數結果。這正是顯式轉換必須謹慎使用的理由。

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