VB.NET and C# 语法比较手册

VB.NET and C# Comparison
This is a quick reference guide to highlight some key syntactical differences between VB.NETand C#. Hope you find this useful!
Thank you to Tom Shelton, Fergus Cooney, and others for your input.

Comments
Data Types
Constants
Enumerations
Operators | Choices
Loops
Arrays
Functions
Exception Handling | Namespaces
Classes / Interfaces
Constructors / Destructors
Objects
Structs | Properties
Delegates / Events
Console I/O
File I/O

---|---|---|---

VB.NET

|

C#

---|---
Comments
_ ' Single line only
Rem Single line only _ |

_ // Single line
/* Multiple
line /
/// XML comments on single line
/
* XML comments on multiple lines */ _

Data Types

_ Value Types
_ Boolean
Byte
Char _ (example: "A"c)
_ Short, Integer, Long
Single, Double
Decimal
Date

_ Reference Types
_ Object
String

Dim x As Integer
Console.WriteLine(x.GetType()) _ ' Prints System.Int32 _
Console.WriteLine(TypeName(x)) ' Prints Integer

_ ' Type conversion
_ Dim numDecimal As Single = 3.5
Dim numInt As Integer
numInt = CType (numDecimal, Integer) _ ' set to 4 (Banker's rounding)
_ numInt = CInt (numDecimal) _ ' same result as CType
_ numInt = Int(numDecimal) ' set to 3 (Int function truncates the decimal)

|

_ Value Types
_ bool
byte, sbyte
char _ (example: 'A')
_ short, ushort, int, uint, long, ulong
float, double
decimal
DateTime (not a built-in C# type)

_ Reference Types
_ object
string

int x;
Console.WriteLine(x.GetType()); _ // Prints System.Int32
_ Console.WriteLine(typeof(int)); _ // Prints System.Int32 _

_ // Type conversion _
double numDecimal = 3.5;
int numInt = (int) numDecimal; _ // set to 3 (truncates decimal) _

Constants
Const MAX_STUDENTS As Integer = 25 | const int MAX_STUDENTS = 25;
Enumerations
Enum Action
Start
[Stop] _ ' Stop is a reserved word
_ 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) _ ' Prints 1 _

Console.WriteLine(Status.Pass) _ ' Prints 70 _

Dim s As Type = GetType(Status)
Console.WriteLine([Enum].GetName(s, Status.Pass)) _ ' Prints Pass _ | 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); _ // Prints "Stop is 1"

_ Console.WriteLine(Status.Pass); _ // Prints Pass _
Operators

_ Comparison
_ = < > <= >= <>

_ Arithmetic
_ + - * /
Mod
\ _ (integer division)
_ ^ (raise to a power)

_ Assignment
_ = += -= *= /= = ^= <<= >>= &=

_ Bitwise
_ And AndAlso Or OrElse Not << >>

_ Logical
_ And AndAlso Or OrElse Not

Note: AndAlso and OrElse are for short-circuiting logical evaluations

_ String Concatenation
_ &

|

_ Comparison
_ == < > <= >= !=

_ Arithmetic
_ + - * /
% _ (mod)
_ / _ (integer division if both operands are ints)
_ Math.Pow(x, y)

_ Assignment
_ = += -= *= /= %= &= |= ^= <<= >>= ++ --

_ Bitwise
_ & | ^ ~ << >>

_ Logical
_ && || !

Note: && and || perform short-circuit logical evaluations

_ String Concatenation
_ +

Choices

greeting = IIf (age < 20, "What's up?", "Hello")

_ ' One line doesn't require "End If", no "Else"
_ If language = "VB.NET" Then langType = "verbose"

_ ' Use : to put two commands on same line
_ If x <> 100 Then x *= 5 : y *= 2

_ ' or to break up any long single command use _
_ If whenYouHaveAReally < longLine And itNeedsToBeBrokenInto2 > Lines Then _
UseTheUnderscore(charToBreakItUp)

_ ' _ If x > 5 Then
x *= y
ElseIf x = 5 Then
x += y
ElseIf x < 10 Then
x -= y
Else
x /= y
End If

Select Case color _ ' Must be a primitive data type
_ Case "pink", "red"
r += 1
Case "blue"
b += 1
Case "green"
g += 1
Case Else
other += 1
End Select

|

greeting = age < 20 ? "What's up?" : "Hello";

if (x != 100) { _ // Multiple statements must be enclosed in {}
_ x *= 5;
y *= 2;
}

_ No need for _ or : since ; is used to terminate each statement. _

**
if ** (x > 5)
x *= y;
else if (x == 5)
x += y;
else if (x < 10)
x -= y;
else
x /= y;

switch (color) { _ // Must be integer or string _
case "pink":
case "red": r++; break; // break is mandatory; no fall-through
case "blue": b++; **break;
** case "green": g++; **break;
** default: other++; break; // break necessary on default
}

Loops
| _ Pre-test Loops: _

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

_ Post-test Loops: _
Do
c += 1
Loop While c < 10 | Do
c += 1
Loop Until c = 10

_ ' Array or collection looping
_ Dim names As String() = {"Fred", "Sue", "Barney"}
For Each s As String In names
Console.WriteLine(s)
Next

_ Pre-test Loops: _

_ // no "until" keyword
_ while (i < 10)
i++;

for (i = 2; i < = 10; i += 2)
Console.WriteLine(i);

_ Post-test Loop:

_ do
i++;
while (i < 10);

_ // Array or collection looping

_ string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
Console.WriteLine(s);

Arrays

Dim nums () As Integer = {1, 2, 3}
For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums(i))
Next

_ ' 4 is the index of the last element, so it holds 5 elements
_ Dim names(4) As String
names(0) = "David"
names(5) = "Bobby" _ ' Throws System.IndexOutOfRangeException _

_ ' Resize the array, keeping the existing values (Preserve is optional)
_ ReDim Preserve names(6)

Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5

Dim jagged ()() As Integer = { _
New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
jagged(0)(4) = 5

|

int [] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]);

_ // 5 is the size of the array
_ string[] names = new string[5];
names[0] = "David";
names[5] = "Bobby"; _ // Throws System.IndexOutOfRangeException _

_ // C# doesn't can't dynamically resize an array. Just copy into new array.
_ string[] names2 = new string[7];
Array.Copy(names, names2, names.Length); _ // or names.CopyTo(names2, 0); _

float [,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int [][] jagged = new int[3][] {
new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

Functions

_ ' Pass by value (in, default), reference (in/out), and reference (out) _
Sub TestFunc( ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)
x += 1
y += 1
z = 5
End Sub

Dim a = 1, b = 1, c As Integer _ ' c set to zero by default _
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c) ' 1 2 5

_ ' Accept variable number of arguments _
Function Sum(ByVal ParamArray nums As Integer()) As Integer
Sum = 0
For Each i As Integer In nums
Sum += i
Next
End Function _ ' Or use Return statement like C#

_ Dim total As Integer = Sum(4, 3, 2, 1) ' returns 10

_ ' Optional parameters must be listed last and must have a default value _
Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
Console.WriteLine("Greetings, " & prefix & " " & name)
End Sub

SayHello("Strangelove", "Dr.")
SayHello("Madonna")

| _ // Pass by value (in, default), reference (in/out), and reference (out)
_ void TestFunc(int x, ref int y, out int z) {
x++;
y++;
z = 5;
}

int a = 1, b = 1, c; // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5

_ // Accept variable number of arguments
_ int Sum( params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}

int total = Sum(4, 3, 2, 1); // returns 10

_ /* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */ _
void SayHello(string name, string prefix) {
Console.WriteLine("Greetings, " + prefix + " " + name);
}

void SayHello(string name) {
SayHello(name, "");
}

Exception Handling

_ ' Deprecated unstructured error handling
_ On Error GoTo MyErrorHandler
...
MyErrorHandler: Console.WriteLine(Err.Description)

Dim ex As New Exception("Something is really wrong.")
Throw ex

Try
y = 0
x = 10 / y
Catch ex As Exception When y = 0 _ ' Argument and When is optional
_ Console.WriteLine(ex.Message)
Finally
Beep()
**End Try
**

|

Exception up = new Exception("Something is really wrong.");
throw up; _ // ha ha _

try {
y = 0;
x = 10 / y;
}
catch (Exception ex) { _ // Argument is optional, no "When" keyword _
Console.WriteLine(ex.Message);
}
finally {
_ // Must use unmanaged MessageBeep API function to beep _
}

Namespaces

Namespace Harding.Compsci.Graphics
...
End Namespace

_ ' or _

Namespace Harding
Namespace Compsci
Namespace Graphics
...
End Namespace
**End Namespace
End Namespace **

Import Harding.Compsci.Graphics

|

namespace Harding.Compsci.Graphics {
...
}

_ // or _

namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}

using Harding.Compsci.Graphics;

Classes / Interfaces

_ Accessibility keywords _
Public
Private
Friend
Protected
Protected Friend
Shared

_ ' Inheritance
_ Class FootballGame
Inherits Competition
...
End Class

_ ' Interface definition
_ Interface IAlarmClock
...
End Interface

_ // Extending an interface
_ Interface IAlarmClock
Inherits IClock
...
End Interface

_ // Interface implementation
_ Class WristWatch
Implements IAlarmClock, ITimer
...
End Class

|

_ Accessibility keywords _
public
private
internal
protected
protected internal
static

_ // Inheritance
_ class FootballGame : Competition {
...
}

_ // Interface definition _
interface IAlarmClock {
...
}

_ // Extending an interface
_ interface IAlarmClock : IClock {
...
}

_ // Interface implementation _
class WristWatch : IAlarmClock, ITimer {
...
}

Constructors / Destructors
Class SuperHero
Private _powerLevel As Integer

Public Sub New ()
_powerLevel = 0
End Sub

Public Sub New (ByVal powerLevel As Integer)
Me._powerLevel = powerLevel
End Sub

Protected Overrides Sub Finalize ()
_ ' Desctructor code to free unmanaged resources _
MyBase.Finalize()
End Sub
End Class |

class SuperHero {
private int _powerLevel;

public SuperHero() {
_powerLevel = 0;
}

public SuperHero(int powerLevel) {
this._powerLevel= powerLevel;
}

~ SuperHero() {
_ // Destructor code to free unmanaged resources.
// Implicitly creates a Finalize method
_ }
}

Objects

Dim hero As SuperHero = New SuperHero
With hero
.Name = "SpamMan"
.PowerLevel = 3
End With

hero.Defend("Laura Jones")
hero.Rest() _ ' Calling Shared method
' or
_ SuperHero.Rest()

Dim hero2 As SuperHero = hero _ ' Both refer to same object _
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name) _ ' Prints WormWoman _

hero = Nothing _ ' Free the object _

If hero Is Nothing Then _
hero = New SuperHero

Dim obj As Object = New SuperHero
If TypeOf obj Is SuperHero Then _
Console.WriteLine("Is a SuperHero object.")

|

SuperHero hero = new SuperHero();

_ // No "With" construct
_ hero.Name = "SpamMan";
hero.PowerLevel = 3;

hero.Defend("Laura Jones");
SuperHero.Rest(); _ // Calling static method _

SuperHero hero2 = hero; _ // Both refer to same object _
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name); _ // Prints WormWoman _

hero = null ; _ // Free the object _

if (hero == null )
hero = new SuperHero();

Object obj = new SuperHero();
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");

Structs

Structure StudentRecord
Public name As String
Public gpa As Single

Public Sub New(ByVal name As String, ByVal gpa As Single)
Me.name = name
Me.gpa = gpa
End Sub
End Structure

Dim stu As StudentRecord = New StudentRecord("Bob", 3.5)
Dim stu2 As StudentRecord = stu

stu2.name = "Sue"
Console.WriteLine(stu.name) _ ' Prints Bob _
Console.WriteLine(stu2.name) _ ' Prints Sue _

| struct StudentRecord {
public string name;
public float gpa;

public StudentRecord(string name, float gpa) {
this.name = name;
this.gpa = gpa;
}
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;

stu2.name = "Sue";
Console.WriteLine(stu.name); _ // Prints Bob
_ Console.WriteLine(stu2.name); _ // Prints Sue _

Properties

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 If
End Set
End Property

foo.Size += 1

| private int _size;

public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}

foo.Size++;

Delegates / Events

Delegate Sub MsgArrivedEventHandler(ByVal message As String)

Event MsgArrivedEvent As MsgArrivedEventHandler

_ ' or to define an event which declares a delegate implicitly
_ Event MsgArrivedEvent(ByVal message As String)

AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
_ ' Won't throw an exception if obj is Nothing
_ RaiseEvent MsgArrivedEvent("Test message")
RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

Imports System.Windows.Forms

Dim WithEvents MyButton As Button _ ' WithEvents can't be used on local variable
_ MyButton = New Button

Private Sub MyButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyButton.Click
MessageBox.Show(Me, "Button was clicked", "Info", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

|

delegate void MsgArrivedEventHandler(string message);

event MsgArrivedEventHandler MsgArrivedEvent;

_ // Delegates must be used with events in C#

_ MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message"); _ // Throws exception if obj is null
_ MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);

using System.Windows.Forms;

Button MyButton = new Button();
MyButton.Click += new System.EventHandler(MyButton_Click);

private void MyButton_Click(object sender, System.EventArgs e) {
MessageBox.Show(this, "Button was clicked", "Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Console I/O

_ Special character constants
_ vbCrLf, vbCr, vbLf, vbNewLine
vbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
""
Chr(65) _ ' Returns 'A' _

Console.Write("What's your name? ")
Dim name As String = Console.ReadLine()
Console.Write("How old are you? ")
Dim age As Integer = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.", name, age)
_ ' or _
Console.WriteLine(name & " is " & age & " years old.")

Dim c As Integer
c = Console.Read() _ ' Read single char _
Console.WriteLine(c) _ ' Prints 65 if user enters "A" _

|

_ Escape sequences
_ \n, \r
\t
\\
"

Convert.ToChar(65) _ // Returns 'A' - equivalent to Chr(num) in VB
// or
_ (char) 65

Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
_ // or
_ Console.WriteLine(name + " is " + age + " years old.");

int c = Console.Read(); _ // Read single char
_ Console.WriteLine(c); _ // Prints 65 if user enters "A" _

File I/O

Imports System.IO

Dim writer As StreamWriter = File.CreateText("c:\myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()

Dim reader As StreamReader = File.OpenText("c:\myfile.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine("line=" & line)
line = reader.ReadLine()
End While
reader.Close()

Dim str As String = "Text data"
Dim num As Integer = 123
Dim binWriter As New BinaryWriter (File.OpenWrite("c:\myfile.dat"))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()

Dim binReader As New BinaryReader (File.OpenRead("c:\myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()

|

using System.IO;

StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();

StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();

string str = "Text data";
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();

BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

Page last modified: 01/14/2004 05:34:59
Please send any corrections or comments to [email protected] .
Home

Published At
Categories with Web编程
Tagged with
comments powered by Disqus