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

C# 型別轉換完整指南:隱含、顯性、Parse/TryParse、as/is 模式比對與效能

     編輯:關於C#

型別轉換分類

類型關鍵字/方法特性範例
隱含轉換自動無資料遺失、編譯器保證安全int i = 10; long l = i;
顯性轉換(T) / Convert.ToX可能資料遺失/溢位、需開發者確認int i = (int)l; int i = Convert.ToInt32(l);
解析/格式化Parse/TryParse字串↔數值、TryParse 不拋例外int.TryParse("123", out int v)
as 運算子as參考型別安全轉換、失敗回傳 nullvar s = obj as string;
is 型別模式isC# 7+ 模式比對、宣告變數if (obj is int i) ...
使用者定義implicit/explicit operator自訂型別間轉換public static implicit operator MyType(int v)

隱含轉換完整對照 (數值型別)

sbyte → short → int → long → float → double
byte  → short → int → long → float → double
      → ushort → uint → ulong → float → double
char  → ushort → uint → ulong → float → double

無符號→有符號需顯性轉換 (可能溢位)。float→double 隱含,double→float 顯性。

顯性轉換與檢查溢位

// 未檢查溢位 (預設)
int i = 2_000_000_000;
int j = i * 2; // 溢位回繞 -294967296

// 檢查溢位區塊
checked {
    int k = i * 2; // 拋 OverflowException
}

// 編譯器選項 /checked+ 整個專案啟用

Parse vs TryParse 效能與用法

// Parse: 失敗拋 FormatException/OverflowException
int v1 = int.Parse("123");        // 正常
// int v2 = int.Parse("abc");     // 例外

// TryParse: 失敗回傳 false,不拋例外 (高效能)
if (int.TryParse(input, out int v3)) {
    // 成功
}

// Span 版本 (C# 7.2+) 避免字串配置
ReadOnlySpan span = "123".AsSpan();
int.TryParse(span, out int v4);

as / is 模式比對最佳實務


// 傳統 as + null 檢查
var str = obj as string;
if (str != null) Console.WriteLine(str.Length);

// C# 7+ is 型別模式 (單一陳述式)
if (obj is string s) Console.WriteLine(s.Length);

// 進階模式
if (obj is int i and > 0) Console.WriteLine($"正整數: {i}");
if (obj is IEnumerable nums) Console.WriteLine(nums.Count());

// switch 運算式結合型別模式
string desc = obj switch {
    int i => $"Int: {i}",
    string s => $"String: {s}",
    null => "Null",
    _ => "Other"
};

自訂型別轉換運算子

public readonly struct Temperature {
    public double Celsius { get; }
    public Temperature(double c) => Celsius = c;

    // 隱含:int → Temperature (安全)
    public static implicit operator Temperature(int c) => new Temperature(c);

    // 顯性:Temperature → int (可能遺失精度)
    public static explicit operator int(Temperature t) => (int)Math.Round(t.Celsius);

    // 使用
    Temperature t1 = 25;          // 隱含
    int c = (int)t1;              // 顯性
}

效能比較建議

  • 熱路徑避免 Convert.ToX (虛擬呼叫、格式提供者開銷),優先 Parse/TryParse 或直接轉型
  • as 僅適用參考型別,實值型別用 Nullable<T> 或模式比對
  • 大量字串解析考慮 Span / Utf8Parser (System.Buffers.Text) 零複製
  • 使用者定義轉換謹慎使用,隱含轉換不可拋例外、不可遺失資訊

隱含轉換圖
顯性轉換
Parse範例
as/is範例
自訂轉換

本文對應《叩響 C# 之門》第 3.5 節型別轉換教學內容

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