So sánh khác nhau điển hình cú pháp của VB.Net và C# (Phan cuoi)

Xem chủ đề cũ hơn Xem chủ đề mới hơn Go down

So sánh khác nhau điển hình cú pháp của VB.Net và C# (Phan cuoi)

Bài gửi  Admin on Thu Jul 08, 2010 7:47 am

Xử lý ngoại lệ
VB.NET
Class Withfinally
PublicSharedSub Main()
Try
Dim x AsInteger= 5
Dim y AsInteger= 0
Dim z AsInteger= x / y
Console.WriteLine(z)
Catch e As DivideByZeroException
System.Console.WriteLine("Error occurred")
Finally
System.Console.WriteLine("Thank you")
EndTry
EndSub
EndClass
C#
class Withfinally{
publicstaticvoid Main() {
try {
int x = 5;
int y = 0;
int z = x/y;
Console.WriteLine(z);
}catch(DivideByZeroException e){
System.Console.WriteLine("Error occurred");
}finally{
System.Console.WriteLine("Thank you");
}
}
}
Không gian tên (Namespaces)
VB.NET
Namespace ASPAlliance.DotNet.Community
...
EndNamespace


'Hoặc


Namespace ASPAlliance
Namespace DotNet
Namespace Community
...
EndNamespace
EndNamespace
EndNamespace


Imports ASPAlliance.DotNet.Community
C#
namespace ASPAlliance.DotNet.Community {
...
}


// Hoặc


namespace ASPAlliance {
namespace DotNet {
namespace Community {
...
}
}
}


using ASPAlliance.DotNet.Community;

Lớp / giao diện (Classes / Interfaces)
VB.NET
'Từ khoá đặc tả truy cập
Public
Private
Friend
Protected
ProtectedFriend
Shared


'Kế thừa
Class Articles
Inherits Authors
...
EndClass


Imports System


Interface IArticle
Sub Show()
EndInterface
_

Class IAuthor
Implements IArticle

PublicSub Show()
System.Console.WriteLine("Show() method Implemented")
EndSub

'Hàm Main theo kiểu của C
PublicOverloadsSharedSub Main()
Main(System.Environment.GetCommandLineArgs())
EndSub


OverloadsPublicSharedSub Main(args() AsString)
Dim author AsNew IAuthor()
author.Show()
EndSub
EndClass
C#
// Từ khoá đặc tả truy cập
public
private
internal
protected
protectedinternal
static


// Kế thừa
class Articles: Authors {
...
}


using System;

interface IArticle{
void Show();
}


class IAuthor:IArticle
{
publicvoid Show()
{
System.Console.WriteLine("Show() method Implemented");
}

//Hàm Main theo kiểu của C
publicstaticvoid Main(){ Main(System.Environment.GetCommandLineArgs())
}
publicstaticvoid Main(string[] args){
IAuthor author =new IAuthor();
author.Show();
}
}


Hàm tạo / hàm huỷ (Constructors / Destructors)
VB.NET
Class TopAuthor
Private _topAuthor AsInteger

PublicSubNew()
_topAuthor = 0
EndSub

PublicSubNew(ByVal topAuthor AsInteger)
Me._topAuthor = topAuthor
EndSub

'Thường sử dụng để giải phóng các tài nguyên unmanaged
ProtectedOverridesSub Finalize()
MyBase.Finalize()
EndSub
EndClass
C#
class TopAuthor {
privateint _topAuthor;

public TopAuthor() {
_topAuthor = 0;
}

public TopAuthor(int topAuthor) {
this._topAuthor= topAuthor
}
//Thường sử dụng để giải phóng các tài nguyên unmanaged
~TopAuthor() {
} //hoặc
ProtectedOverridevoid Finalize(){
Base.Finalize()
}
}
Đối tượng
VB.NET
Dim author As TopAuthor =New TopAuthor
With author
.Name ="Han"
.AuthorRanking = 3
EndWith

author.Rank("Vip")
'Truy xuất đến thành phần tĩnh có thể thông qua đối tượng
author.Demote()
'hoặc qua tên lớp
TopAuthor.Rank()

'Hai tham chiếu đến cùng một đối tượng
Dim author2 As TopAuthor = author
author2.Name ="Diep"
System.Console.WriteLine(author2.Name) 'Prints Diep

'Free the object
author =Nothing


If author IsNothingThen _
author =New TopAuthor


Dim obj AsObject=New TopAuthor
IfTypeOf obj Is TopAuthor Then _
System.Console.WriteLine("Is a TopAuthor object.")
C#
TopAuthor author =new TopAuthor();

//Không có từ khoá tương tự with
author.Name ="Steven";
author.AuthorRanking = 3;


author.Rank("Scott");
//Truy xuất đến thành phần tĩnh phải thông qua tên lớp
TopAuthor.Demote()


//Hai tham chiếu đến cùng một đối tượng
TopAuthor author2 = author
author2.Name ="Diep";
System.Console.WriteLine(author2.Name) //Prints Diep

//Free the object
author =null


if (author == null)
author =new TopAuthor();


Object obj =new TopAuthor();
if (obj is TopAuthor)
SystConsole.WriteLine("Is a TopAuthor object.");



Cấu trúc (Structs)
VB.NET
Structure AuthorRecord
Public name AsString
Public rank AsSingle

PublicSubNew(ByVal name AsString, ByVal rank AsSingle)
Me.name = name
Me.rank = rank
EndSub
EndStructure


Dim author As AuthorRecord =New AuthorRecord("Han", 8.Cool
Dim author2 As AuthorRecord = author

author2.name ="Tinh"
System.Console.WriteLine(author.name) 'Prints Han
System.Console.WriteLine(author2.name) 'Prints Tinh
C#
struct AuthorRecord {
publicstring name;
publicfloat rank;

public AuthorRecord(string name, float rank) {
this.name = name;
this.rank = rank;
}
}



AuthorRecord author =new AuthorRecord("Han", 8.Cool;
AuthorRecord author2 = author

author.name ="Tinh";
SystemConsole.WriteLine(author.name); //Prints Han
System.Console.WriteLine(author2.name); //Prints Tinh


Thuộc tính (Properties)
VB.NET
Private _size AsInteger

PublicProperty Size() AsInteger
Get
Return _size
EndGet
Set (ByVal Value AsInteger)
If Value < 0 Then
_size = 0
Else
_size = Value
EndIf
EndSet
EndProperty


foo.Size += 1


Imports System
Class [Date]

PublicPropertyDay() AsInteger
Get
Returnday
EndGet
Set
day= value
EndSet
EndProperty
PrivatedayAsInteger


PublicPropertyMonth() AsInteger
Get
Returnmonth
EndGet
Set
month= value
EndSet
EndProperty
PrivatemonthAsInteger


PublicPropertyYear() AsInteger
Get
Returnyear
EndGet
Set
year= value
EndSet
EndProperty
PrivateyearAsInteger


PublicFunction IsLeapYear(yearAsInteger) AsBoolean
Return(IfyearMod 4 = 0 ThenTrueElseFalse)
EndFunction

PublicSub SetDate(dayAsInteger, monthAsInteger,
yearAsInteger)
Me.day=day
Me.month=month
Me.year=year
EndSub
EndClass
C#
privateint _size;

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



foo.Size++;


using System;
class Date
{
publicint Day{
get {
return day;
}
set {
day = value;
}
}
int day;


publicint Month{
get {
return month;
}
set {
month = value;
}
}
int month;


publicint Year{
get {
return year;
}
set {
year = value;
}
}
int year;


publicbool IsLeapYear(int year)
{
return year%4== 0 ? true: false;
}
publicvoid SetDate (int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
}
Delegates / Events
VB.NET
DelegateSub MsgArrivedEventHandler(ByVal message
AsString)


Event MsgArrivedEvent As MsgArrivedEventHandler


'Hoặc định nghĩa một event tường minh là delegate
Event MsgArrivedEvent(ByVal message AsString)


AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
'Không ném ra ngoại lệ nếu obj=nothing
RaiseEvent MsgArrivedEvent("Test message")
RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback


Imports System.Windows.Forms


'WithEvents không được sử dụng với biến cục bộ
DimWithEvents MyButton As Button
MyButton =New Button


PrivateSub 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)
EndSub
C#
delegatevoid MsgArrivedEventHandler(string message);


event MsgArrivedEventHandler MsgArrivedEvent;


//Delegates phải được khai báo với events


MsgArrivedEvent += new MsgArrivedEventHandler
(My_MsgArrivedEventCallback);
//Ném ra ngoại lệ nếu obj=null
MsgArrivedEvent("Test message");
MsgArrivedEvent -= new MsgArrivedEventHandler
(My_MsgArrivedEventCallback);




using System.Windows.Forms;


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


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

Nhập xuất từ bàn phím
VB.NET
'Các hằng kí tự đặc biệt
vbCrLf, vbCr, vbLf, vbNewLine
vbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
""
Chr(65) 'Returns 'A'


System.Console.Write("Nhap ten: ")
Dim name AsString= System.Console.ReadLine()
System.Console.Write("Tuoi: ")
Dim age AsInteger=Val(System.Console.ReadLine())
System.Console.WriteLine("{0} len {1} tuoi.", name, age)
'or
System.Console.WriteLine(name & " len " & age & " tuoi.")


Dim c AsInteger
c = System.Console.Read() 'Doc 1 ki tu tu ban phim
System.Console.WriteLine(c) 'In ra 65 neu nhap "A"
C#
//Các kí tự thoát
\n, \r
\t
\\
\


Convert.ToChar(65) //Returns 'A'
//hoặc
(char) 65

System.Console.Write("Nhap ten: ");
string name = SYstem.Console.ReadLine();
System.Console.Write("Nhap tuoi: ");
int age = Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine("{0} len {1} tuoi.", name, age);
//or
System.Console.WriteLine(name +" len "+ age +" tuoi.");

int c = System.Console.Read(); //'Doc 1 ki tu tu ban phim
System.Console.WriteLine(c); //'In ra 65 neu nhap "A"


Nhập xuất I/O
VB.NET
Imports System.IO


'Ghi ra tệp văn bản
Dim writer As StreamWriter = File.CreateText
("c:\myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()


'Đọc tất cả các dòng từ tệp văn bản
Dim reader As StreamReader = File.OpenText
("c:\myfile.txt")
Dim line AsString= reader.ReadLine()
WhileNot line IsNothing
Console.WriteLine(line)
line = reader.ReadLine()
EndWhile
reader.Close()


'Ghi các kiểu nguyên thuỷ (ghi kiểu nhị phân)
DimstrAsString="Text data"
Dim num AsInteger= 123
Dim binWriter AsNew BinaryWriter(File.OpenWrite
("c:\myfile.dat"))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()


'Đọc các kiểu nguyên thuỷ (đọc kiểu nhị phân)
Dim binReader AsNew BinaryReader(File.OpenRead
("c:\myfile.dat"))
str= binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()
C#
using System.IO;


// Ghi ra tệp văn bản
StreamWriter writer = File.CreateText
("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();


// Đọc tất cả các dòng từ tệp văn bản
StreamReader reader = File.OpenText
("c:\\myfile.txt");
string line = reader.ReadLine();
while (line !=null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();


//Ghi các kiểu nguyên thuỷ (ghi kiểu nhị phân)
string str ="Text data";
int num = 123;
BinaryWriter binWriter =new BinaryWriter(File.OpenWrite
("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();

// Đọc các kiểu nguyên thuỷ (đọc kiểu nhị phân)
BinaryReader binReader =new BinaryReader(File.OpenRead
("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();
Laughing Laughing Laughing Laughing

Admin
Admin

Tổng số bài gửi: 4
Join date: 08/07/2010

Xem lý lịch thành viên http://aspnet.forum0.net

Về Đầu Trang Go down

Xem chủ đề cũ hơn Xem chủ đề mới hơn Về Đầu Trang

- Similar topics

Permissions in this forum:
Bạn không có quyền trả lời bài viết