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

C# 型別轉換基礎:隱性與顯性轉換完整說明

     編輯:關於C語言

隱性轉換

編譯器保證資訊不遺失、不會拋例外,自動發生:


byte n = byte.MaxValue; // 255
short n1 = n;  // 255
int n2 = n;    // 255
long n3 = n;   // 255
// 方向:byte → short → int → long → float → double → decimal
// 以及衍生類別 → 基底類別、實作類別 → 介面

顯性轉換 (Cast)

可能資訊遺失、可能拋例外,需開發者明確確認:


ulong n = ulong.MaxValue; // 18446744073709551615
byte n1 = (byte)n;     // 255 (截尾)
ushort n2 = (ushort)n; // 65535 (截尾)
uint n3 = (uint)n;     // 4294967295 (截尾)
// 方向:double → float → long → int → short → byte 等縮小轉換

轉換方法比較

方式適用失敗行為
Cast `(T)`基本型別、參考型別之間例外/截尾
`Convert.ToXxx`物件/字串 → 基本型別例外 (可捕捉)
`TryParse`字串 → 數值回傳 `false`,不拋例外
`as`參考型別向下轉型回傳 `null`
`is`型別測試 (C# 7+ 型別模式)回傳 `bool`

使用者定義轉換

類別/結構可定義 `implicit`/`explicit` 運算子:


public struct Digit
{
    public byte Value;
    public static implicit operator byte(Digit d) => d.Value;
    public static explicit operator Digit(byte b) => new Digit { Value = b };
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved