Xem mẫu
- So sánh những điểm khác biệt nổi bật về cú pháp
của VB.Net và C#
Chú thích trong chương trình
VB.NET C#
'Chỉ một dòng chú thích // Chỉ một dòng chú thích
Rem Chỉ một dòng chú thích /* Chú thích
trên nhiều dòng */
/// XML một dòng chú thích theo chuẩn XML
/** XML nhiều dòng chú
thích theo chuẩn XML */
Cấu trúc chương trình
VB.NET C#
Imports System using System
Namespace MyNameSpace Namespace MyNameSpace
Class HelloWorld {
'Điểm bắt đầu của ứng dụng theo kiểu của C class HelloWorld
Public Overloads Shared Sub Main() {
Main(System.Environment.GetCommandLineArgs()) //Điểm bắt đầu của ứng dụng theo kiểu C
End Sub static void Main(){
Main(System.Environment.GetCommandLineArgs());
Overloads Shared Sub Main(args() As String) }
System.Console.WriteLine("Hello World") static void Main(string[] args){
End Sub System.Console.WriteLine("Hello World")
End Class }
}
}
Các kiểu dữ liệu
VB.NET C#
'Các kiểu nguyên thuỷ //Các kiểu nguyên thuỷ
Boolean bool
Byte byte, sbyte
Char (example: "A") char (example: 'A')
Short, Integer, Long short, ushort, int, uint, long, ulong
Single, Double float, double
Decimal decimal
Date DateTime
'Kiểu tham chiếu // Kiểu tham chiếu
Object object
String string
Dim x As Integer int x;
System.Console.WriteLine(x.GetType()) Console.WriteLine(x.GetType())
System.Console.WriteLine(TypeName(x)) Console.WriteLine(typeof(int))
'Chuyển kiểu // Chuyển kiểu
Dim d As Single = 3.5 float d = 3.5;
Dim i As Integer = CType (d, Integer) int i = (int) d
i = CInt (d)
- i = Int(d)
Hằng số
VB.NET C#
Const MAX_AUTHORS As Integer = 25 const int MAX_AUTHORS = 25;
ReadOnly MIN_RANK As Single = 5.00 readonly float MIN_RANKING = 5.00F;
Kiểu liệt kê
VB.NET C#
Enum Action enum Action {Start, Stop, Rewind, Forward};
Start enum Status {Flunk = 50, Pass = 70, Excel = 90};
'Stop là từ khoá nên bao trong cặp ngoặc []
[Stop]
Rewind
Forward
End Enum
Enum Status
Flunk = 50
Pass = 70
Excel = 90
End Enum
Action a = Action.Stop;
Dim a As Action = Action.Stop if (a != Action.Start)
If a Action.Start Then _ //In ra "Stop is 1"
'In ra "Stop is 1" System.Console.WriteLine(a + " is " + (int) a);
System.Console.WriteLine(a.ToString & " is " & a)
// In ra 70
'In ra70 System.Console.WriteLine((int) Status.Pass);
System.Console.WriteLine(Status.Pass) // In ra Pass
' In ra Pass System.Console.WriteLine(Status.Pass);
System.Console.WriteLine(Status.Pass.ToString())
Enum Weekdays enum Weekdays
Saturday {
Sunday Saturday, Sunday, Monday, Tuesday, Wednesday,
Monday Thursday, Friday
Tuesday }
Wednesday
Thursday
Friday
End Enum
Phép toán
VB.NET C#
'Các phép quan hệ // Các phép quan hệ
= < > = == < > = !=
'Các phép toán số học // Các phép toán số học
+ - * / + - * /
Mod % (mod)
\ (integer division) / (integer division if both operands are ints)
^ (raise to a power) Math.Pow(x, y)
'Các phép gán // Các phép gán
= += -= *= /= \= ^= = &= = += -= *= /= %= &= |= ^= = ++ --
'Các phép toán trên bit // Các phép toán trên bit
And AndAlso Or OrElse Not > & | ^ ~ >
- 'Các phép toán logic // Các phép toán logic
And AndAlso Or OrElse Not && || !
'Nối xâu // Nối xâu
& +
Biểu thức lựa chọn
VB.NET C#
greeting = IIf(age < 20, "Đã yêu", "Chưa yêu") greeting = age < 20 ? "Đã yêu" : "Chưa yêu";
'Phát biểu trên 1 dòng thì không cần End If
If language = "VB.NET" Then langType = "verbose"
'Sử dụng : để đặt nhiều lệnh trên 1 dòng
If x 100 And y < 5 Then x *= 5 : y *= 2
'Phép gán tắt đã có trong VB.Net --> rất tiện dụng if (x != 100 && y < 5)
If x 100 And y < 5 Then {
x *= 5 // Nhiều phát biểu cần nằm trong {}
y *= 2 x *= 5;
End If y *= 2;
}
If x > 5 Then if (x > 5)
x *= y x *= y;
ElseIf x = 5 Then else if (x == 5)
x += y x += y;
ElseIf x < 10 Then else if (x < 10)
x -= y x -= y;
Else else
x /= y x /= y;
End If
'Biểu thức điều kiện phải thuộc kiểu nguyên thuỷ //Biểu thức điều kiện phảicó kiểu nguyên hoặc xâu
Select Case color switch (color)
Case "black", "red" {
r += 1 case "black":
Case "blue" case "red": r++;
b += 1 break;
Case "green" case "blue"
g += 1 break;
Case Else case "green": g++;
other += 1 break;
End Select default: other++;
break;
}
Các vòng lặp
VB.NET C#
'Vòng lặp kiểm tra điều kiện trước //Vòng lặp kiểm tra điều kiện trước
While c < 10 while (c < 10)
c += 1 c++;
End While hoặc
Do Until c = 10
c += 1
Loop
- 'Vòng xác định //Vòng xác định
For c = 2 To 10 Step 2 for (i = 2; i < = 10; i += 2)
System.Console.WriteLine(c) System.Console.WriteLine(i);
Next
'Vòng lặp kiểm tra điều kiện sau //Vòng lặp kiểm tra điều kiện sau
Do While c < 10 do
c += 1 i++;
Loop while (i < 10);
'Vòng lặp duyệt mảng hoặc tập hợp //Vòng lặp duyệt mảng hoặc tập hợp
Dim names As String() = {"han", "tinh", "diep"} string[] names = {"han", "tinh", "diep"};
For Each s As String In names foreach (string s in names)
System.Console.WriteLine(s) System.Console.WriteLine(s);
Next
Mảng
VB.NET C#
'Khai báo và khởi tạo mảng //Khai báo và khởi tạo mảng
Dim nums() As Integer = {1, 2, 3} int[] nums = {1, 2, 3};
For i As Integer = 0 To nums.Length - 1 for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums(i)) Console.WriteLine(nums[i]);
Next
'Khai báo mảng gồm 5 phần tử, phần tử đầu có chỉ số là //Khai báo mảng gồm 5 phần tử, phần tử đầu có chỉ số
1 và phần tử cuối cùng có chỉ số 4 là 1 và phần tử cuối cùng có chỉ số 4
Dim names(4) As String string[] names = new string[5];
names(0) = "mot" names[0] = "mot";
'Ném ra ngoại lệ System.IndexOutOfRangeException //Ném ra ngoại lệ System.IndexOutOfRangeException
names(5) = "nam" names[5] = "nam"
//Không thể thay đổi kích cỡ của mảng
//Cần phải copy vô mảng mới
'Thay đổi kích cỡ của mảng mà giá trị của mảng vẫn giữ string[] names2 = new string[7];
nguyên giá trị nếu có tuỳ chọn Preserve // or names.CopyTo(names2, 0);
ReDim Preserve names(6) Array.Copy(names, names2, names.Length);
//Khai báo mảng nhiều chiều
float[,] twoD = new float[rows, cols];
'Khai báo mảng nhiều chiều twoD[2,0] = 4.5;
Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5 hoặc khai báo
int[][] jagged = new int[3][] {
hoặc khai báo new int[5], new int[2], new int[3] };
Dim jagged()() As Integer = { _ jagged[0][4] = 5;
New Integer(4) {}, New Integer(1) {}, New Integer(2)
{} }
jagged(0)(4) = 5
Hàm, thủ tục
VB.NET C#
'Mặc định truyền theo tham trị(in), ByRef=tham trị //Mặc định truyền theo tham trị (in), có 2 kiểu truyền
Sub TestFunc(ByVal x As Integer, ByRef y As Integer, tham chiếu ref =(in/out) và out=(out)
ByRef z As Integer) void TestFunc(int x, ref int y, out int z) {
x += 1 x++;
y += 1 y++;
z = 5 z = 5;
End Sub }
// c không cần khởi tạo trước khi gọi nhưng, nhưng
'c mang giá trị mặc định là 0 b thì cần
int a = 1, b = 1, c; TestFunc(a, ref b, out c);
Dim a = 1, b = 1, c As Integer System.Console.WriteLine("{0} {1} {2}", a, b, c); //
- TestFunc(a, b, c) 1 2 5
System.Console.WriteLine("{0} {1} {2}", a, b, c) '1 2
5
//Khai báo hàm có thể truyền vào nhiều giá trị
int Sum(params int[] nums) {
'Khai báo hàm có thể truyền vào nhiều giá trị int sum = 0;
foreach (int i in nums)
Function Sum(ByVal ParamArray nums As Integer()) As sum += i;
Integer return sum;
Sum = 0 }
For Each i As Integer In nums
Sum += i
Next int total = Sum(4, 3, 2, 1); // total=10
End Function
Dim total As Integer = Sum(4, 3, 2, 1) ' total=10 /* C# doesn't support optional arguments/parameters.
Just create two different versions of the same
function. */
'Tham số tuỳ chọn nếu có phải nằm cuối danh sách và nó void SayHello(string name, string prefix) {
phải mang giá trị System.Console.WriteLine("Greetings, " + prefix + "
Sub SayHello(ByVal name As String, " + name);
Optional ByVal prefix As String = "") }
System.Console.WriteLine("Greetings, " & prefix
& " " & name) void SayHello(string name) {
End Sub SayHello(name, "");
}
SayHello("Steven", "Dr.")
SayHello("Steven", "Dr.") SayHello("SuOk")
SayHello("SuOk")
Xử lý ngoại lệ
VB.NET C#
Class Withfinally class Withfinally{
Public Shared Sub Main() public static void Main() {
Try try {
Dim x As Integer = 5 int x = 5;
Dim y As Integer = 0 int y = 0;
Dim z As Integer = x / y int z = x/y;
Console.WriteLine(z) Console.WriteLine(z);
Catch e As DivideByZeroException }catch(DivideByZeroException e){
System.Console.WriteLine("Error occurred") System.Console.WriteLine("Error occurred");
Finally }finally{
System.Console.WriteLine("Thank you") System.Console.WriteLine("Thank you");
End Try }
End Sub }
End Class }
Không gian tên (Namespaces)
VB.NET C#
Namespace ASPAlliance.DotNet.Community namespace ASPAlliance.DotNet.Community {
... ...
End Namespace }
'Hoặc // Hoặc
Namespace ASPAlliance namespace ASPAlliance {
Namespace DotNet namespace DotNet {
Namespace Community namespace Community {
... ...
End Namespace }
End Namespace }
End Namespace }
- Imports ASPAlliance.DotNet.Community using ASPAlliance.DotNet.Community;
Lớp / giao diện (Classes / Interfaces)
VB.NET C#
'Từ khoá đặc tả truy cập // Từ khoá đặc tả truy cập
Public public
Private private
Friend internal
Protected protected
Protected Friend protected internal
Shared static
'Kế thừa // Kế thừa
Class Articles class Articles: Authors {
Inherits Authors ...
... }
End Class
using System;
Imports System
interface IArticle{
void Show();
Interface IArticle }
Sub Show()
End Interface
_ class IAuthor:IArticle
{
Class IAuthor public void Show()
Implements IArticle {
System.Console.WriteLine("Show() method
Public Sub Show() Implemented");
System.Console.WriteLine("Show() method }
Implemented")
End Sub //Hàm Main theo kiểu của C
public static void Main(){
'Hàm Main theo kiểu của C Main(System.Environment.GetCommandLineArgs())
Public Overloads Shared Sub Main() }
Main(System.Environment.GetCommandLineArgs()) public static void Main(string[] args){
End Sub IAuthor author = new IAuthor();
author.Show();
}
Overloads Public Shared Sub Main(args() As String) }
Dim author As New IAuthor()
author.Show()
End Sub
End Class
Hàm tạo / hàm huỷ (Constructors / Destructors)
VB.NET C#
Class TopAuthor class TopAuthor {
Private _topAuthor As Integer private int _topAuthor;
Public Sub New() public TopAuthor() {
_topAuthor = 0 _topAuthor = 0;
End Sub }
Public Sub New(ByVal topAuthor As Integer) public TopAuthor(int topAuthor) {
Me._topAuthor = topAuthor this._topAuthor= topAuthor
End Sub }
//Thường sử dụng để giải phóng các tài nguyên
'Thường sử dụng để giải phóng các tài nguyên unmanaged
unmanaged ~TopAuthor() {
Protected Overrides Sub Finalize() } //hoặc
- MyBase.Finalize() Protected Override void Finalize(){
End Sub Base.Finalize()
End Class }
}
Đối tượng
VB.NET C#
Dim author As TopAuthor = New TopAuthor TopAuthor author = new TopAuthor();
With author
.Name = "Han" //Không có từ khoá tương tự with
.AuthorRanking = 3 author.Name = "Steven";
End With author.AuthorRanking = 3;
author.Rank("Vip")
'Truy xuất đến thành phần tĩnh có thể thông qua đối author.Rank("Scott");
tượng //Truy xuất đến thành phần tĩnh phải thông qua tên
author.Demote() lớp
'hoặc qua tên lớp TopAuthor.Demote()
TopAuthor.Rank()
'Hai tham chiếu đến cùng một đối tượng //Hai tham chiếu đến cùng một đối tượng
Dim author2 As TopAuthor = author TopAuthor author2 = author
author2.Name = "Diep" author2.Name = "Diep";
System.Console.WriteLine(author2.Name) 'Prints Diep System.Console.WriteLine(author2.Name) //Prints Diep
'Free the object //Free the object
author = Nothing author = null
If author Is Nothing Then _ if (author == null)
author = New TopAuthor author = new TopAuthor();
Dim obj As Object = New TopAuthor Object obj = new TopAuthor();
If TypeOf obj Is TopAuthor Then _ if (obj is TopAuthor)
System.Console.WriteLine("Is a TopAuthor object.") SystConsole.WriteLine("Is a TopAuthor object.");
Cấu trúc (Structs)
VB.NET C#
Structure AuthorRecord struct AuthorRecord {
Public name As String public string name;
Public rank As Single public float rank;
Public Sub New(ByVal name As String, ByVal rank As public AuthorRecord(string name, float rank) {
Single) this.name = name;
Me.name = name this.rank = rank;
Me.rank = rank }
End Sub }
End Structure
Dim author As AuthorRecord = New AuthorRecord("Han", AuthorRecord author = new AuthorRecord("Han", 8.8);
8.8) AuthorRecord author2 = author
Dim author2 As AuthorRecord = author
author.name = "Tinh";
author2.name = "Tinh" SystemConsole.WriteLine(author.name); //Prints Han
System.Console.WriteLine(author.name) 'Prints Han System.Console.WriteLine(author2.name); //Prints Tinh
System.Console.WriteLine(author2.name) 'Prints Tinh
Thuộc tính (Properties)
- VB.NET C#
Private _size As Integer private int _size;
Public Property Size() As Integer public int Size {
Get get {
Return _size return _size;
End Get }
Set (ByVal Value As Integer) set {
If Value < 0 Then if (value < 0)
_size = 0 _size = 0;
Else else
_size = Value _size = value;
End If }
End Set }
End Property
foo.Size += 1 foo.Size++;
Imports System using System;
Class [Date] class Date
{
Public Property Day() As Integer public int Day{
Get get {
Return day return day;
End Get }
Set set {
day = value day = value;
End Set }
End Property }
Private day As Integer int day;
Public Property Month() As Integer public int Month{
Get get {
Return month return month;
End Get }
Set set {
month = value month = value;
End Set }
End Property }
Private month As Integer int month;
Public Property Year() As Integer public int Year{
Get get {
Return year return year;
End Get }
Set set {
year = value year = value;
End Set }
End Property }
Private year As Integer int year;
Public Function IsLeapYear(year As Integer) As public bool IsLeapYear(int year)
Boolean {
Return(If year Mod 4 = 0 Then True Else False) return year%4== 0 ? true: false;
End Function }
public void SetDate (int day, int month, int
Public Sub SetDate(day As Integer, month As year)
Integer, {
year As Integer) this.day = day;
Me.day = day this.month = month;
Me.month = month this.year = year;
Me.year = year }
End Sub }
End Class
- Delegates / Events
VB.NET C#
Delegate Sub MsgArrivedEventHandler(ByVal message delegate void MsgArrivedEventHandler(string message);
As String)
event MsgArrivedEventHandler MsgArrivedEvent;
Event MsgArrivedEvent As MsgArrivedEventHandler
//Delegates phải được khai báo với events
'Hoặc định nghĩa một event tường minh là delegate
Event MsgArrivedEvent(ByVal message As String)
MsgArrivedEvent += new MsgArrivedEventHandler
(My_MsgArrivedEventCallback);
AddHandler MsgArrivedEvent, AddressOf //Ném ra ngoại lệ nếu obj=null
My_MsgArrivedCallback MsgArrivedEvent("Test message");
'Không ném ra ngoại lệ nếu obj=nothing MsgArrivedEvent -= new MsgArrivedEventHandler
RaiseEvent MsgArrivedEvent("Test message") (My_MsgArrivedEventCallback);
RemoveHandler MsgArrivedEvent, AddressOf
My_MsgArrivedCallback
Imports System.Windows.Forms using System.Windows.Forms;
'WithEvents không được sử dụng với biến cục bộ Button MyButton = new Button();
Dim WithEvents MyButton As Button MyButton.Click += new
MyButton = New Button System.EventHandler(MyButton_Click);
Private Sub MyButton_Click(ByVal sender As private void MyButton_Click(object sender,
System.Object, _ System.EventArgs e) {
ByVal e As System.EventArgs) Handles MyButton.Click MessageBox.Show(this, "Button was clicked", "Info",
MessageBox.Show(Me, "Button was clicked", "Info", _ MessageBoxButtons.OK,
MessageBoxButtons.OK, MessageBoxIcon.Information) MessageBoxIcon.Information);
End Sub }
Nhập xuất từ bàn phím
VB.NET C#
'Các hằng kí tự đặc biệt //Các kí tự thoát
vbCrLf, vbCr, vbLf, vbNewLine \n, \r
vbNullString \t
vbTab \vbBack vbFormFeed
vbVerticalTab
"" Convert.ToChar(65) //Returns 'A'
Chr(65) 'Returns 'A' //hoặc
(char) 65
System.Console.Write("Nhap ten: ") System.Console.Write("Nhap ten: ");
Dim name As String = System.Console.ReadLine() string name = SYstem.Console.ReadLine();
System.Console.Write("Tuoi: ") System.Console.Write("Nhap tuoi: ");
Dim age As Integer = Val(System.Console.ReadLine()) int age = Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine("{0} len {1} tuoi.", name, System.Console.WriteLine("{0} len {1} tuoi.", name,
age) age);
'or //or
System.Console.WriteLine(name & " len " & age & " System.Console.WriteLine(name + " len " + age + "
tuoi.") tuoi.");
int c = System.Console.Read(); //'Doc 1 ki tu tu ban
Dim c As Integer phim
c = System.Console.Read() 'Doc 1 ki tu tu ban phim System.Console.WriteLine(c); //'In ra 65 neu nhap
System.Console.WriteLine(c) 'In ra 65 neu nhap "A" "A"
- Nhập xuất I/O
VB.NET C#
Imports System.IO using System.IO;
'Ghi ra tệp văn bản // Ghi ra tệp văn bản
Dim writer As StreamWriter = File.CreateText StreamWriter writer = File.CreateText
("c:\myfile.txt") ("c:\\myfile.txt");
writer.WriteLine("Out to file.") writer.WriteLine("Out to file.");
writer.Close() writer.Close();
'Đọc tất cả các dòng từ tệp văn bản // Đọc tất cả các dòng từ tệp văn bản
Dim reader As StreamReader = File.OpenText StreamReader reader = File.OpenText
("c:\myfile.txt") ("c:\\myfile.txt");
Dim line As String = reader.ReadLine() string line = reader.ReadLine();
While Not line Is Nothing while (line != null) {
Console.WriteLine(line) Console.WriteLine(line);
line = reader.ReadLine() line = reader.ReadLine();
End While }
reader.Close() reader.Close();
'Ghi các kiểu nguyên thuỷ (ghi kiểu nhị phân) //Ghi các kiểu nguyên thuỷ (ghi kiểu nhị phân)
Dim str As String = "Text data" string str = "Text data";
Dim num As Integer = 123 int num = 123;
Dim binWriter As New BinaryWriter(File.OpenWrite BinaryWriter binWriter = new
("c:\myfile.dat")) BinaryWriter(File.OpenWrite
binWriter.Write(str) ("c:\\myfile.dat"));
binWriter.Write(num) binWriter.Write(str);
binWriter.Close() binWriter.Write(num);
binWriter.Close();
'Đọc các kiểu nguyên thuỷ (đọc kiểu nhị phân) // Đọc các kiểu nguyên thuỷ (đọc kiểu nhị phân)
Dim binReader As New BinaryReader(File.OpenRead BinaryReader binReader = new
("c:\myfile.dat")) BinaryReader(File.OpenRead
str = binReader.ReadString() ("c:\\myfile.dat"));
num = binReader.ReadInt32() str = binReader.ReadString();
binReader.Close() num = binReader.ReadInt32();
binReader.Close();
nguon tai.lieu . vn