針對雙語言開發者或遷移項目,整理 C# 與 VB.NET 在註釋、數據類型、常量、枚舉、運算符、流程控制、循環、數組、函數、異常處理、命名空間、類/介面、構造函數、對象、結構體、屬性、委托/事件、控制台 IO、文件 IO 等 18 個維度的語法差異,便於快速查閱與互通。
| 特性 | VB.NET | C# |
|---|---|---|
| 單行註釋 | ' Comment | // Comment |
| 多行註釋 | 不支援(用多行 ') | /* Comment */ |
| 整數類型 | Short, Integer, Long | short, int, long |
| 字符類型 | Char ("A") | char ('A') |
| 布爾類型 | Boolean | bool |
| 常量聲明 | Const MAX = 25 | const int MAX = 25; |
| 只讀字段 | ReadOnly MIN = 5.0 | readonly float MIN = 5.0f; |
| 枚舉定義 | Enum Action : Start, [Stop], End Enum | enum Action { Start, Stop, End }; |
| 三元運算符 | IIf(cond, t, f) | cond ? t : f |
| 字符串拼接 | & | + |
| 邏輯與/或 | AndAlso / OrElse | && / || |
| If 語句 | If ... Then ... Else ... End If | if (...) { } else { } |
| Select/Case | Select Case ... Case ... End Select | switch (...) { case ...: break; } |
| For 循環 | For i = 1 To 10 Step 2 ... Next | for (int i=1; i<=10; i+=2) { } |
| For Each | For Each s In arr ... Next | foreach (var s in arr) { } |
| 數組聲明 | Dim a(4) As String | string[] a = new string[5]; |
| 動態擴容 | ReDim Preserve a(6) | Array.Resize 或新建數組拷貝 |
| 函數參數 | ByVal/ByRef/ParamArray | 默認值傳遞 / ref / out / params |
| 可選參數 | Optional ByVal p As String = "" | 不支援(需重載) |
| 異常捕獲 | Catch ex As Exception When ... | catch (Exception ex) { } |
| 命名空間 | Namespace ... End Namespace | namespace ... { } |
| 類繼承 | Class A Inherits B | class A : B { } |
| 介面實現 | Class A Implements I | class A : I { } |
| 構造函數 | Sub New() | public A() { } |
| 解構函數 | Protected Overrides Sub Finalize() | ~A() { } |
| 屬性語法 | Property P() As Int ... Get/Set ... End Property | public int P { get; set; } |
| 事件聲明 | Event E As Delegate / RaiseEvent E(...) | event Delegate E; E?.Invoke(...) |
| 文件讀寫 | StreamReader/Writer, BinaryReader/Writer | 同類別,語法風格不同 |
雙語言團隊建議制定統一編碼規範,關鍵邏輯以單一語言實現,避免混合帶來的維護成本。本表可作為代碼審查、語言遷移、面試復習的快速參考。