`
sogotobj
  • 浏览: 612678 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

[转]C#和VB.net语法对比图

阅读更多

[转]C#和VB.net语法对比图

C#和VB.net的语法相差还是比较大的. 可能你会C#,可能你会VB.

将它们俩放在一起对比一下你就会很快读懂,并掌握另一门语言.

相信下面这张表会对你帮助很大.

Comments

VB.NET

'Single line only
Rem Single line only

C#

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

Data Types

VB.NET

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


'Reference Types
Object
String



Dim x As Integer
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(TypeName(x)) 


'Type conversion
Dim d As Single = 3.5
Dim i As Integer = CType (d, Integer)
i = CInt (d)
i = Int(d)

C#

//Value Types
bool
byte, sbyte
char (example: 'A')
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime 


//Reference Types
object
string



int x;
Console.WriteLine(x.GetType())
Console.WriteLine(typeof(int)) 


//Type conversion
float d = 3.5;
int i = (int) d

Constants

VB.NET

Const MAX_AUTHORS As Integer = 25
ReadOnly MIN_RANK As Single = 5.00

C#

const int MAX_AUTHORS = 25;
readonly float MIN_RANKING = 5.00;

Enumerations

VB.NET

Enum Action
Start
'Stop is a reserved word
[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 _
'Prints "Stop is 1" 
 System.Console.WriteLine(a.ToString & " is " & a)

'Prints 70
System.Console.WriteLine(Status.Pass)
'Prints Pass
System.Console.WriteLine(Status.Pass.ToString())

C#

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











Action a = Action.Stop;
if (a != Action.Start)
//Prints "Stop is 1"
 System.Console.WriteLine(a + " is " + (int) a); 

// Prints 70
System.Console.WriteLine((int) Status.Pass); 
// Prints Pass
System.Console.WriteLine(Status.Pass);

Operators

VB.NET

'Comparison
= < > <= >= <> 


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


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


'Bitwise
AndAndAlso OrOrElse Not << >> 


'Logical
And AndAlso OrOrElseNot 


'String Concatenation
& 

C#

//Comparison
== < > <= >= != 


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


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


//Bitwise
& | ^~ << >> 


//Logical
&& || ! 


//String Concatenation
+

Choices

VB.NET

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 And y < 5 Then x *= 5 : y *= 2 


'Preferred
If x <> 100 And y < 5 Then
 x *= 5
 y *= 2
End If 




'or to break up any long single command use _
If henYouHaveAReally <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 


'Must be a primitive data type
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 (x != 100 && y < 5)
{
 // Multiple statements must be enclosed in {}
 x *= 5;
 y *= 2;
} 








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



//Must be integer or string
switch (color)
{
 case "black":
 case "red": r++;
 break;
 case "blue"
 break;
 case "green": g++;
 break;
 default: other++;
 break;
}

Loops

VB.NET

'Pre-test Loops:
While c < 10
 c += 1
End While Do Until c = 10
 c+= 1
Loop 


'Post-test Loop:
Do While c < 10
 c += 1
Loop 


For c = 2 To 10 Step 2
 System.Console.WriteLine(c)
Next 



'Array or collection looping
Dim names As String() = {"Steven", "SuOk", "Sarah"}
For Each s As String In names
 System.Console.WriteLine(s)
Next

C#

//Pre-test Loops: while (i < 10)
 i++;
for (i = 2; i < = 10; i += 2)
 System.Console.WriteLine(i); 






//Post-test Loop:
do
 i++;
while (i < 10);








// Array or collection looping
string[] names = {"Steven", "SuOk", "Sarah"};
foreach (string s in names)
 System.Console.WriteLine(s);

Arrays

VB.NET

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) = "Steven"
'Throws System.IndexOutOfRangeException
names(5) = "Sarah"


'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

C#

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] = "Steven";
// Throws System.IndexOutOfRangeException
names[5] = "Sarah"


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



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


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

Functions

VB.NET

'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 


'c set to zero by default

Dim a = 1, b = 1, c As Integer
TestFunc(a, b, c)
System.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 a 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 = "")
System.Console.WriteLine("Greetings, " & prefix
& " " & name)
End Sub


SayHello("Steven", "Dr.")
SayHello("SuOk")

C#

// 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);
System.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'tsupport optional arguments/parameters.
Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
 System.Console.WriteLine("Greetings, " 
               + prefix + " " + name);
}

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

Exception Handling

VB.NET

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

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


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

C#





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{
 // Do something
}

Namespaces

VB.NET

Namespace ASPAlliance.DotNet.Community
 ...
End Namespace 


'or 


Namespace ASPAlliance 
 Namespace DotNet
 Namespace Community
 ...
 End Namespace
 End Namespace
End Namespace 


Imports ASPAlliance.DotNet.Community

C#

namespace ASPAlliance.DotNet.Community {
 ...
} 


// or 


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


using ASPAlliance.DotNet.Community;

Classes / Interfaces

VB.NET

'Accessibility keywords
Public
Private
Friend
Protected
Protected Friend
Shared 


'Inheritance
Class Articles
 Inherits Authors
 ...
End Class 


'Interface definition
Interface IArticle
 ...
End Interface 


'Extending an interface
Interface IArticle
 Inherits IAuthor
 ...
End Interface 


'Interface implementation</span>
Class PublicationDate
 Implements</strong> IArticle, IRating
 ...
End Class

C#

//Accessibility keywords
public
private
internal
protected
protected internal
static 


//Inheritance
class Articles: Authors {
 ...
} 



//Interface definition
interface IArticle {
 ...
} 


//Extending an interface
interface IArticle: IAuthor {
 ...
} 



//Interface implementation
class PublicationDate: IArticle, IRating {
 ...
}

Constructors / Destructors

VB.NET

Class TopAuthor
 Private _topAuthor As Integer

 Public Sub New()
 _topAuthor = 0
 End Sub

 Public Sub New(ByVal topAuthor As Integer)
 Me._topAuthor = topAuthor
 End Sub

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

C#

class TopAuthor {
 private int _topAuthor;

 public TopAuthor() {
_topAuthor = 0;
 }

 public TopAuthor(int topAuthor) {
 this._topAuthor= topAuthor
 }

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

Objects

VB.NET

Dim author As TopAuthor = New TopAuthor
With author
 .Name = "Steven"
 .AuthorRanking = 3
End With

author.Rank("Scott")
author.Demote() 'Calling Shared method
'or
TopAuthor.Rank() 


Dim author2 As TopAuthor = author 'Both refer to same object
author2.Name = "Joe"
System.Console.WriteLine(author2.Name) 'Prints Joe 


author = Nothing 'Free the object 


If author Is Nothing Then _
 author = New TopAuthor 


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

C#

TopAuthor author = new TopAuthor();

//No "With" construct
author.Name = "Steven";
author.AuthorRanking = 3; 


author.Rank("Scott");
TopAuthor.Demote() //Calling static method 




TopAuthor author2 = author //Both refer to same object
author2.Name = "Joe";
System.Console.WriteLine(author2.Name) //Prints Joe 


author = null //Free the object 


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


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

Structs

VB.NET

Structure AuthorRecord
 Public name As String
 Public rank As Single

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


Dim author As AuthorRecord = New AuthorRecord("Steven", 8.8)
Dim author2 As AuthorRecord = author

author2.name = "Scott"
System.Console.WriteLine(author.name) 'Prints Steven
System.Console.WriteLine(author2.name) 'Prints Scott

C#

struct AuthorRecord {
 public string name;
 public float rank;

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



AuthorRecord author = new AuthorRecord("Steven", 8.8);
AuthorRecord author2 = author

author.name = "Scott";
SystemConsole.WriteLine(author.name); //Prints Steven
System.Console.WriteLine(author2.name); //Prints Scott

Properties

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


foo.Size += 1

C#

private int _size;

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



foo.Size++;

Delegates / Events

VB.NET

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 


'WithEvents can't be used on local variable
Dim WithEvents MyButton As Button
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

C#

delegate void MsgArrivedEventHandler(string message); 


event MsgArrivedEventHandler MsgArrivedEvent; 


//Delegates must be used with events in C#


MsgArrivedEvent += new MsgArrivedEventHandler
(My_MsgArrivedEventCallback);
//Throws exception if obj is null
MsgArrivedEvent("Test message");
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

VB.NET

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


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

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

C#

//Escape sequences
n, r
t

 


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


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


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

File I/O

VB.NET

Imports System.IO 


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


'Read all lines from text file
Dim reader As StreamReader = File.OpenText
("c:myfile.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
 Console.WriteLine(line)
 line = reader.ReadLine()
End While
reader.Close() 


'Write out to binary file
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() 


'Read from binary file
Dim binReader As New BinaryReader(File.OpenRead
("c:myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()

C#

using System.IO; 


//Write out to text file
StreamWriter writer = File.CreateText
("c:myfile.txt");
writer.WriteLine("Out to file.");
writer.Close(); 


//Read all lines from text file
StreamReader reader = File.OpenText
("c:myfile.txt");
string line = reader.ReadLine();
while (line != null) {
 Console.WriteLine(line);
 line = reader.ReadLine();
}
reader.Close(); 


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


//Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead
("c:myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

注:本文转自http://www.lemongtree.com/280.html.aspx

分享到:
评论

相关推荐

    C++ Java C#.net VB.net 语法对比

    C++ Java C#.net VB.net 四种常用语言的各种语法对比,语法大全

    VB.NET与C#語法不同点对比表(經典)

    这篇文章主要讨论vb.net语言和c#.net语言在语法上的不同,vb.net和c#.net有一系列微妙的差异,变量的申明和赋值,数据类型,语句终止的方式,语句块的表述,使用的变量括号,操作符的不同,条件语句的不同,错误处理...

    一个用于制作C# 或者VB.NET编辑器

    SharpDevelop 是一个用于制作 C# 或者 VB.NET 的项目而设计的一个编 辑器,同时,这个编辑器本身就是使用 C# 开发的,而且公开了全部源代 码,因此这个工具本身也是学习 C# 以及软件开发规范的一个很好材料。...

    VB.net与C#的语法区别(非常全面)

    VB.net与C#的语法区别Program Structure、Comments、Data Types、Constants、Enumerations、Operators、Choices、Loops、Arrays、Functions、Strings、Exception Handling、Namespaces、Classes / Interfaces等

    C#VB.NET语法的比较

    C#VB.NET语法的比较适合C#转vb或者vb转C#

    VB.NET 和 C# 语法比较

    VB.NET 和 C# 语法比较,可帮助VB.NET 开发者在转身C#时,进行语法比较,加快学习进程。

    VB.NET与C#语法比较

    VB.NET与C#语法比较 VB.NET、C#.NET语法 .NET

    vb.net和c#语法对比

    VB.NET C# Imports System using System; Namespace Hello namespace Hello {  Class HelloWorld  public class HelloWorld {  Overloads Shared Sub Main(ByVal args() As String)  public static void Main...

    SharpDevelop-C#或者VB.NET项目而设计编辑器

    SharpDevelop 是一个用于制作C#或者VB.NET的项目而设计的一个编辑器,同时,这个编辑器本身就是使用C#开发的,而且公开了全部源代码,因此这个工具本身也是学习C#以及软件开发规范的一个很好材料。  SharpDevelop ...

    SharpDevelop 中文版 C#\VB.NET 的项目开发工具

    Office XP 以及 VS.NET,这个编辑器 可以支持书写 C#、ASP.NET、ADO.NET、XML、HTML 等多种代码, 支持基 于项目或者是文件的开发,可以对 C#、HTML、ASP、ASP.NET、VB.NET、V Bscript、XML 提供彩色语法显示支持,...

    VB.NET与C#語法对比表

    语法上,vb.net和c#.net是两种不同的语言,就像visual basic,visual c,visual c++是不同的语言一样。C#.net看上去更像是visual c,visual c++和jave,vb.net看上去像是visual basic,这两种语言最大的区别在于以下几点...

    VB.NET编辑器) v3.1.1.5327 多语言版.zip

    SharpDevelop是一个用于制作C#或者VB.NET的项目而设计的一个编辑器,同时,这个编辑器本身就是使用C#开发的,而且公开了全部源代码,因此这个工具本身也是学习C#以及软件开发规范的一个很好材料。SharpDevelop中的...

    构建与测试.NET正则表达式的软件RegexDesigner.NET

    regexdesigner.net是一个强力的可视化工具,可以帮助我们构建与测试.NET正则表达式,RegexDesigner...为所有正则操作生成C#和VB.NET代码 生成编译的程序集 联机帮助。 此软件为英文软件,需要.net framework支持。

    C#&VB对照完整表

    C#与VB语法对照表,熟悉两种语言非常快的方式,C#与VB.net项目

    附录A-VB.NET 和C#语法简明比较.pdf

    对VB和C#进行对比,加深两种语言的认识

    ASP.NET 2.0(C#)基础教程

    微软推出的Web开发技术,开发者可以使用C#、VB.NET、JavaScript等. NET支持的语言进行开发。本书将使用C#作为ASP.NET开发语言。 本书将介绍C#基本语法(包括变量、数据类型、表达式、运算符等)、 面向对象C#...

    RegexDesigner.NET 正则表达式开源工具 支持中文 修改版

    regexdesigner.net是一个强力的可视化工具,可以帮助我们构建与测试.NET正则表达式,RegexDesigner.NET让我们将我们开发出的正则表达式集成到我们的应用程序,可以方便的生成C#或VB.NET代码并编译成程序集 ...

    SharpDevelop_3.2.1.6466

    SharpDevelop 是一个用于制作C#或者VB.NET的项目而设计的一个编辑器,同时,这个编辑器本身就是使用C#开发的,而且公开了全部源代码,因此这个工具本身也是学习C#以及软件开发规范的一个很好材料。 SharpDevelop 这...

    asp.net知识库

    实现C#和VB.net之间的相互转换 深入剖析ASP.NET组件设计]一书第三章关于ASP.NET运行原理讲述的补白 asp.net 运行机制初探(httpModule加载) 利用反射来查看对象中的私有变量 关于反射中创建类型实例的两种方法 ASP...

    FlexGrid for .NET--.NET版的网格控件

    使用绑定模式的网格时,它将显示ADO.NET数据源获得的数据,而在非绑定模式时,网格本身就可以管理数据。您只需要:绑定网格到一个现存的数据结构,使用经过计算的&quot;;;;虚拟&quot;;;;字段,执行数据检验和按要求...

Global site tag (gtag.js) - Google Analytics