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

VB.NET 與 C# 語法對照表:快速掌握雙語言開發

     編輯:關於C語言

前言

.NET 平台上最主流的兩大語言 VB.NET 與 C# 雖共用同一個 CLR 與基礎類別庫,但語法風格差異極大。本文整理核心語法對照表,幫助開發者快速在兩語言間切換與閱讀程式碼。

1. 註解

VB.NETC#
' 單行註解
Rem 單行註解
// 單行
/* 多行 */
/// XML 文件註解
/** 多行 XML 註解 */

2. 資料類型

分類VB.NETC#
實值型別Boolean, Byte, Char, Short, Integer, Long, Single, Double, Decimal, Datebool, byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double, decimal, DateTime
參考型別Object, Stringobject, string
宣告範例Dim x As Integerint x;
取得型別x.GetType() / TypeName(x)x.GetType() / typeof(int)
轉型CType(d, Integer) / CInt(d) / Int(d)(int)d

3. 常數與唯讀欄位

VB.NETC#
Const MAX_AUTHORS As Integer = 25
ReadOnly MIN_RANK As Single = 5.0
const int MAX_AUTHORS = 25;
readonly float MIN_RANK = 5.0f;

4. 列舉

' VB.NET
Enum Action
    Start
    [Stop] ' 保留字需加括號
    Rewind
    Forward
End Enum

Enum Status
    Flunk = 50
    Pass = 70
    Excel = 90
End Enum

Dim a As Action = Action.Stop
If a <> Action.Start Then Console.WriteLine(a.ToString() & " is " & a) ' 輸出 "Stop is 1"
Console.WriteLine(Status.Pass)        ' 70
Console.WriteLine(Status.Pass.ToString()) ' "Pass"

// C#
enum Action { Start, Stop, Rewind, Forward };
enum Status { Flunk = 50, Pass = 70, Excel = 90 };

Action a = Action.Stop;
if (a != Action.Start)
    Console.WriteLine(a + " is " + (int)a); // "Stop is 1"
Console.WriteLine((int)Status.Pass);        // 70
Console.WriteLine(Status.Pass);             // "Pass"

5. 運算子

類別VB.NETC#
比較=, <, >, <=, >=, <>==, <, >, <=, >=, !=
算術+, -, *, /, Mod, ^+, -, *, /, %, Math.Pow()
指派=, +=, -=, *=, /=, ^=, <<=, >>=, &==, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, ++, --
位元And, Or, Not, <<, >>&, |, ^, ~, <<, >>
邏輯AndAlso, OrElse, Not&&, ||, !
字串串接&+

6. 條件判斷

' VB.NET
greeting = IIf(age < 20, "What's up?", "Hello")
If language = "VB.NET" Then langType = "verbose"
If x <> 100 And y < 5 Then x *= 5 : y *= 2
If x > 5 Then x *= y ElseIf x = 5 Then x += y ElseIf x < 10 Then x -= y Else x /= y
Select Case color
    Case "black", "red" : r += 1
    Case "blue" : b += 1
    Case "green" : g += 1
    Case Else : other += 1
End Select

// C#
greeting = age < 20 ? "What's up?" : "Hello";
if (language == "C#") langType = "concise";
if (x != 100 && y < 5) { x *= 5; y *= 2; }
if (x > 5) x *= y; else if (x == 5) x += y; else if (x < 10) x -= y; else x /= y;
switch (color) {
    case "black": case "red": r++; break;
    case "blue": b++; break;
    case "green": g++; break;
    default: other++; break;
}

7. 迴圈

' VB.NET
While c < 10 : c += 1 : End While
Do Until c = 10 : c += 1 : Loop
Do While c < 10 : c += 1 : Loop
For c = 2 To 10 Step 2 : Console.WriteLine(c) : Next
For Each s As String In names : Console.WriteLine(s) : Next

// C#
while (c < 10) c++;
do c++; while (c < 10);
for (int c = 2; c <= 10; c += 2) Console.WriteLine(c);
foreach (string s in names) Console.WriteLine(s);

8. 陣列

' VB.NET
Dim nums() As Integer = {1, 2, 3}
For i = 0 To nums.Length - 1 : Console.WriteLine(nums(i)) : Next
Dim names(4) As String ' 5 元素
names(0) = "Steven"
ReDim Preserve names(6) ' 動態調整保留資料
Dim twoD(2, 2) As Single
Dim jagged()() As Integer = { New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }

// C#
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++) Console.WriteLine(nums[i]);
string[] names = new string[5]; // 固定大小 5
names[0] = "Steven";
// C# 陣列不可動態調整,需手動複製
string[] names2 = new string[7];
Array.Copy(names, names2, names.Length);
float[,] twoD = new float[3, 3];
int[][] jagged = new int[3][] { new int[5], new int[2], new int[3] };

9. 函式/方法

' VB.NET
Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)
    x += 1 : y += 1 : z = 5
End Sub

Function Sum(ByVal ParamArray nums As Integer()) As Integer
    For Each i In nums : Sum += i : Next
End Function
Dim total = Sum(4, 3, 2, 1) ' 10

Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
    Console.WriteLine("Greetings, " & prefix & " " & name)
End Sub

// C#
void TestFunc(int x, ref int y, out int z) { x++; y++; z = 5; }
int a=1, b=1, c; TestFunc(a, ref b, out c); // a=1,b=2,c=5

int Sum(params int[] nums) { int sum=0; foreach(int i in nums) sum+=i; return sum; }
int total = Sum(4, 3, 2, 1); // 10

// C# 無選擇性參數 (舊版本),需多載
void SayHello(string name, string prefix) => Console.WriteLine($"Greetings, {prefix} {name}");
void SayHello(string name) => SayHello(name, "");

10. 例外處理

' VB.NET
Try
    y = 0 : x = 10 / y
Catch ex As Exception When y = 0
    Console.WriteLine(ex.Message)
Finally
    DoSomething()
End Try

// C#
try { y = 0; x = 10 / y; }
catch (Exception ex) { Console.WriteLine(ex.Message); }
finally { DoSomething(); }

11. 命名空間

' VB.NET
Namespace ASPAlliance.DotNet.Community ... End Namespace
Imports ASPAlliance.DotNet.Community

// C#
namespace ASPAlliance.DotNet.Community { ... }
using ASPAlliance.DotNet.Community;

12. 類別與介面

' VB.NET
Class Articles Inherits Authors ... End Class
Interface IArticle ... End Interface
Interface IArticle Inherits IAuthor ... End Interface
Class PublicationDate Implements IArticle, IRating ... End Class

// C#
class Articles : Authors { ... }
interface IArticle { ... }
interface IArticle : IAuthor { ... }
class PublicationDate : IArticle, IRating { ... }

13. 建構子與解構子

' VB.NET
Class TopAuthor
    Private _topAuthor As Integer
    Public Sub New() : _topAuthor = 0 : End Sub
    Public Sub New(topAuthor As Integer) : _topAuthor = topAuthor : End Sub
    Protected Overrides Sub Finalize() : MyBase.Finalize() : End Sub
End Class

// C#
class TopAuthor {
    private int _topAuthor;
    public TopAuthor() { _topAuthor = 0; }
    public TopAuthor(int topAuthor) { _topAuthor = topAuthor; }
    ~TopAuthor() { /* 釋放非受控資源 */ }
}

14. 物件操作

' VB.NET
Dim author As New TopAuthor()
With author : .Name = "Steven" : .AuthorRanking = 3 : End With
author.Rank("Scott")
TopAuthor.Demote() ' Shared 方法
Dim author2 As TopAuthor = author
author2.Name = "Joe"
author = Nothing
If author Is Nothing Then author = New TopAuthor()
Dim obj As Object = New TopAuthor()
If TypeOf obj Is TopAuthor Then Console.WriteLine("Is TopAuthor")

// C#
var author = new TopAuthor();
author.Name = "Steven"; author.AuthorRanking = 3;
author.Rank("Scott");
TopAuthor.Demote(); // static
var author2 = author;
author2.Name = "Joe";
author = null;
if (author == null) author = new TopAuthor();
object obj = new TopAuthor();
if (obj is TopAuthor) Console.WriteLine("Is TopAuthor");

15. 結構

' VB.NET
Structure AuthorRecord
    Public name As String
    Public rank As Single
    Public Sub New(name As String, rank As Single)
        Me.name = name : Me.rank = rank
    End Sub
End Structure
Dim author As New AuthorRecord("Steven", 8.8)
Dim author2 = author
author2.name = "Scott"
// author.name 仍為 "Steven" (值型別複製)

// C#
struct AuthorRecord {
    public string name;
    public float rank;
    public AuthorRecord(string name, float rank) { this.name = name; this.rank = rank; }
}
var author = new AuthorRecord("Steven", 8.8f);
var author2 = author;
author2.name = "Scott";
// author.name 仍為 "Steven"

16. 屬性

' VB.NET
Private _size As Integer
Public Property Size() As Integer
    Get : Return _size : End Get
    Set(ByVal Value As Integer)
        If Value < 0 Then _size = 0 Else _size = Value
    End Set
End Property
foo.Size += 1

// C#
private int _size;
public int Size {
    get => _size;
    set => _size = value < 0 ? 0 : value;
}
foo.Size++;

17. 委派與事件

' VB.NET
Delegate Sub MsgArrivedEventHandler(ByVal message As String)
Event MsgArrivedEvent As MsgArrivedEventHandler
' 或隱含委派
Event MsgArrivedEvent(ByVal message As String)
AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
RaiseEvent MsgArrivedEvent("Test")
RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

' WithEvents 自動連結
Dim WithEvents MyButton As Button
Private Sub MyButton_Click(...) Handles MyButton.Click ... End Sub

// C#
delegate void MsgArrivedEventHandler(string message);
event MsgArrivedEventHandler MsgArrivedEvent;
MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test");
MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);

var MyButton = new Button();
MyButton.Click += new EventHandler(MyButton_Click);
void MyButton_Click(object sender, EventArgs e) { ... }

18. 主控台 I/O

' VB.NET
Console.Write("Name? ") : Dim name = Console.ReadLine()
Console.Write("Age? ") : Dim age = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.", name, age)
Dim c = Console.Read() ' 讀單一字元

// C#
Console.Write("Name? "); string name = Console.ReadLine();
Console.Write("Age? "); int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
int c = Console.Read();

19. 檔案 I/O

' VB.NET
Imports System.IO
Dim writer = File.CreateText("c:\myfile.txt") : writer.WriteLine("Out") : writer.Close()
Dim reader = File.OpenText("c:\myfile.txt")
Dim line = reader.ReadLine()
While line IsNot Nothing : Console.WriteLine(line) : line = reader.ReadLine() : End While
reader.Close()

// C#
using System.IO;
var writer = File.CreateText(@"c:\myfile.txt"); writer.WriteLine("Out"); writer.Close();
var reader = File.OpenText(@"c:\myfile.txt");
string line;
while ((line = reader.ReadLine()) != null) Console.WriteLine(line);
reader.Close();

結語

掌握上述對照表,即可在 VB.NET 與 C# 專案間自由切換。實務上建議團隊統一單一語言以降低認知負荷,但跨語言維護舊專案時,此表可作為快速查閱的利器。

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