兩大 .NET 語言在類型檢查、轉換、空值處理上關鍵字雖同名但語意不同,初學者極易混淆。本文系統整理 9 大主題,附雙語言對照表與 IL 驗證細節。
| 方式 | C# | VB.NET | 說明 |
|---|---|---|---|
| 實例方法 | obj.GetType() | obj.GetType() | 回傳執行期確切類型 |
| 關鍵字/運算子 | typeof(int) | GetType(Integer) | 編譯期靜態取得,無實例開銷 |
| 靜態方法 | Type.GetType("System.Int32") | Type.GetType("System.Int32") | 字串載入,需完整命名空間 |
陷阱:VB 的 GetType 關鍵字對應 C# 的 typeof,而非 obj.GetType()。
// C#
Type t = typeof(int); // 靜態取得 Type
bool b = obj is int; // 型別相容檢查
string s = obj as string; // 安全轉換,失敗回傳 null
' VB.NET
Dim t As Type = GetType(Integer) ' 靜態取得 Type
Dim b As Boolean = TypeOf obj Is Integer ' 型別相容檢查(僅參考類型)
Dim i As Integer = 3
Dim obj As Object = i
Console.WriteLine(TypeOf obj Is Integer) ' True
| 語言 | 關鍵字 | 用途 | 範例 |
|---|---|---|---|
| C# | is | 型別相容檢查(含繼承、介面、拆箱) | obj is IDisposable |
| VB | Is | 參考相等比較(等同 C# ReferenceEquals) | obj1 Is obj2 |
⚠️ VB 的 TypeOf ... Is 才對應 C# 的 is。
as:安全參考轉換,失敗回傳 null(僅參考/可為 null 型別)As:宣告子句(變數、參數、泛型約束),非運算子| 分類 | C# | VB.NET | 備註 |
|---|---|---|---|
| 隱含轉換 | 自動 | 自動 | 無資料遺失 |
| 顯式轉換 | (int)d | CType(d, Integer) / CInt(d) | VB CType 為內聯函式,效能佳 |
| Convert 類別 | Convert.ToInt32(o) | Convert.ToInt32(o) | 共用,處理 null、格式轉換 |
| Parse 系列 | int.Parse(s) / int.TryParse | Integer.Parse(s) / Integer.TryParse | 字串→數值,TryParse 避免例外 |
| 安全轉換 | o as string | TryCast(o, String) | 失敗回傳 null/Nothing |
| 強制轉換 | (string)o | DirectCast(o, String) | 需繼承關係,否則拋出例外 |
| 特性 | C# null | VB Nothing |
|---|---|---|
| 語意 | 參考類型無值 | 任何類型的預設值 |
| 值類型指派 | int? x = null(需可為 null) | Dim i As Integer = Nothing → 0 |
| 比較運算子 | == null / != null | = Nothing / Is Nothing / IsNot Nothing |
| 預設值取得 | default(int) → 0 | Nothing 即為預設值 |
VB 編譯器會自動將 Nothing 依語境轉為 0、False、""、null,C# 需顯式使用 default(T)。
// C#
int? a = null;
bool has = a.HasValue;
int val = a.GetValueOrDefault();
int val2 = a ?? 5; // null 聯合運算子
' VB.NET (VS2017+)
Dim a? As Integer = Nothing
Dim has = a.HasValue
Dim val = a.GetValueOrDefault()
Dim val2 = If(a, 5) ' 無 ?? 運算子,用 If
// 資料庫欄位為 NULL 時,回傳 DBNull.Value
object val = row["Column"];
if (val != DBNull.Value) { /* 有資料 */ }
// VB
If row("Column") IsNot DBNull.Value Then ...
DBNull.Value == null → false,兩者完全不同物件。
| 情境 | C# | VB.NET |
|---|---|---|
| 判斷物件為特定類型 | obj is MyClass | TypeOf obj Is MyClass |
| 安全轉換並檢查 | var s = obj as string; if(s!=null)... | Dim s = TryCast(obj, String); If s IsNot Nothing Then... |
| 字串轉整數(含錯誤處理) | int.TryParse(s, out int v) | Integer.TryParse(s, v) |
| 取得型別預設值 | default(T) | Nothing |
| 可為 null 實值類型取值或預設 | nullable ?? fallback | If(nullable, fallback) |
掌握雙語言關鍵字的**語意邊界**,能避免移植程式碼時的邏輯錯誤。核心口訣:C# 重「運算子」,VB 重「宣告/函式」;C# null 唯參考,VB Nothing 通吃預設值。