C#和VB.net的语法相差还是比较大的. 可能你会C#,可能你会VB. 将它们俩放在一起对比一下你就会很快读懂,并掌握另一门语言. 相信下面这张图会对你帮助很大. Comments VB.NET C# Data Types VB.NET Reference Types Dim x As Integer Type conversion C# //Reference Types int x; //Type conversion Constants VB.NET C# Enumerations VB.NET Enum Status Dim a As Action = Action.Stop Prints 70 C# Action a = Action.Stop; // Prints 70 Operators VB.NET Arithmetic Assignment Bitwise Logical String Concatenation C# //Arithmetic //Assignment //Bitwise //Logical //String Concatenation Choices VB.NET One line doesnt require “End If”, no “Else” Use: to put two commands on same line Preferred or to break up any long single command use _ If x > 5 Then Must be a primitive data type C# if (x != 100 && y < 5) if (x > 5) //Must be integer or string Loops VB.NET Post-test Loop: For c = 2 To 10 Step 2 Array or collection looping C# //Post-test Loop: // Array or collection looping Arrays VB.NET 4 is the index of the last element, so it holds 5 elements Resize the array, keeping the existing Dim twoD(rows-1, cols-1) As Single Dim jagged()() As Integer = { _ C# // 5 is the size of the array // C# cant dynamically resize an array. float[,] twoD = new float[rows, cols]; int[][] jagged = new int[3][] { Functions VB.NET c set to zero by default Dim a = 1, b = 1, c As Integer Accept variable number of arguments Dim total As Integer = Sum(4, 3, 2, 1) returns 10 Optional parameters must be listed last SayHello(“Steven”, “Dr.”) C# int a = 1, b = 1, c; // c doesnt need initializing // Accept variable number of arguments int total = Sum(4, 3, 2, 1); // returns 10 /* C# doesnt support optional arguments/parameters. void SayHello(string name) { Exception Handling VB.NET Dim ex As New Exception(“Something has really gone wrong.”) Try C# try{ Namespaces VB.NET or Namespace ASPAlliance Imports ASPAlliance.DotNet.Community C# // or namespace ASPAlliance { using ASPAlliance.DotNet.Community; Classes / Interfaces VB.NET Inheritance Interface definition Extending an interface Interface implementation</span> C# //Inheritance //Interface definition //Extending an interface //Interface implementation Constructors / Destructors VB.NET Public Sub New() Public Sub New(ByVal topAuthor As Integer) Protected Overrides Sub Finalize() C# public TopAuthor() { public TopAuthor(int topAuthor) { ~TopAuthor() { Objects VB.NET author.Rank(“Scott”) Dim author2 As TopAuthor = author Both refer to same object author = Nothing Free the object If author Is Nothing Then _ Dim obj As Object = New TopAuthor C# //No “With” construct author.Rank(“Scott”); TopAuthor author2 = author //Both refer to same object author = null //Free the object if (author == null) Object obj = new TopAuthor(); Structs VB.NET Public Sub New(ByVal name As String, ByVal rank As Single) Dim author As AuthorRecord = New AuthorRecord(“Steven”, 8.8) author2.name = “Scott” C# public AuthorRecord(string name, float rank) { AuthorRecord author = new AuthorRecord(“Steven”, 8.8); author.name = “Scott”; Properties VB.NET Public Property Size() As Integer foo.Size += 1 C# public int Size { foo.Size++; Delegates / Events VB.NET Event MsgArrivedEvent As MsgArrivedEventHandler or to define an event which declares a AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback Imports System.Windows.Forms WithEvents cant be used on local variable Private Sub MyButton_Click(ByVal sender As System.Object, _ C# event MsgArrivedEventHandler MsgArrivedEvent; //Delegates must be used with events in C# MsgArrivedEvent += new MsgArrivedEventHandler using System.Windows.Forms; Button MyButton = new Button(); private void MyButton_Click(object sender, Console I/O VB.NET System.Console.Write(“Whats your name? “) Dim c As Integer C# Convert.ToChar(65) System.Console.Write(“Whats your name? “); int c = System.Console.Read(); //Read single char File I/O VB.NET Write out to text file Read all lines from text file Write out to binary file Read from binary file C# //Write out to text file //Read all lines from text file //Write out to binary file //Read from binary file
Single line only
Rem Single line only
// Single line
/* Multiple
line */
/// XML comments on single line
/** XML comments on multiple lines */
Value Types
Boolean
Byte
Char (example: “A”)
Short, Integer, Long
Single, Double
Decimal
Date
Object
String
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(TypeName(x))
Dim d As Single = 3.5
Dim i As Integer = CType (d, Integer)
i = CInt (d)
i = Int(d)
//Value Types
bool
byte, sbyte
char (example: A)
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime
object
string
Console.WriteLine(x.GetType())
Console.WriteLine(typeof(int))
float d = 3.5;
int i = (int) d
Const MAX_AUTHORS As Integer = 25
ReadOnly MIN_RANK As Single = 5.00
const int MAX_AUTHORS = 25;
readonly float MIN_RANKING = 5.00;
Enum Action
Start
Stop is a reserved word
[Stop]
Rewind
Forward
End Enum
Flunk = 50
Pass = 70
Excel = 90
End Enum
If a <> Action.Start Then _
Prints “Stop is 1″
System.Console.WriteLine(a.ToString & ” is ” & a)
System.Console.WriteLine(Status.Pass)
Prints Pass
System.Console.WriteLine(Status.Pass.ToString())
enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};
if (a != Action.Start)
//Prints “Stop is 1″
System.Console.WriteLine(a + ” is ” + (int) a);
System.Console.WriteLine((int) Status.Pass);
// Prints Pass
System.Console.WriteLine(Status.Pass);
Comparison
= < > <= >= <>
+ – * /
Mod
(integer division)
^ (raise to a power)
= += -= *= /= = ^= <<= >>= &=
And AndAlso Or OrElse Not << >>
And AndAlso Or OrElse Not
&
//Comparison
== < > <= >= !=
+ – * /
% (mod)
/ (integer division if both operands are ints)
Math.Pow(x, y)
= += -= *= /= %= &= |= ^= <<= >>= ++ —
& | ^ ~ << >>
&& || !
+
greeting = IIf(age < 20, “Whats up?”, “Hello”)
If language = “VB.NET” Then langType = “verbose”
If x <> 100 And y < 5 Then x *= 5 : y *= 2
If x <> 100 And y < 5 Then
x *= 5
y *= 2
End If
If henYouHaveAReally < longLine And _
itNeedsToBeBrokenInto2 > Lines Then _
UseTheUnderscore(charToBreakItUp)
x *= y
ElseIf x = 5 Then
x += y
ElseIf x < 10 Then
x -= y
Else
x /= y
End If
Select Case color
Case “black”, “red”
r += 1
Case “blue”
b += 1
Case “green”
g += 1
Case Else
other += 1
End Select
greeting = age < 20 ? “Whats up?” : “Hello”;
{
// Multiple statements must be enclosed in {}
x *= 5;
y *= 2;
}
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”
break;
case “green”: g++;
break;
default: other++;
break;
}
Pre-test Loops:
While c < 10
c += 1
End While Do Until c = 10
c += 1
Loop
Do While c < 10
c += 1
Loop
System.Console.WriteLine(c)
Next
Dim names As String() = {“Steven”, “SuOk”, “Sarah”}
For Each s As String In names
System.Console.WriteLine(s)
Next
//Pre-test Loops: while (i < 10)
i++;
for (i = 2; i < = 10; i += 2)
System.Console.WriteLine(i);
do
i++;
while (i < 10);
string[] names = {“Steven”, “SuOk”, “Sarah”};
foreach (string s in names)
System.Console.WriteLine(s);
Dim nums() As Integer = {1, 2, 3}
For i As Integer = 0 To nums.Length – 1
Console.WriteLine(nums(i))
Next
Dim names(4) As String
names(0) = “Steven”
Throws System.IndexOutOfRangeException
names(5) = “Sarah”
values (Preserve is optional)
ReDim Preserve names(6)
twoD(2, 0) = 4.5
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]);
string[] names = new string[5];
names[0] = “Steven”;
// Throws System.IndexOutOfRangeException
names[5] = “Sarah”
//Just copy into new array.
string[] names2 = new string[7];
// or names.CopyTo(names2, 0);
Array.Copy(names, names2, names.Length);
twoD[2,0] = 4.5;
new int[5], new int[2], new int[3] };
jagged[0][4] = 5;
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
TestFunc(a, b, c)
System.Console.WriteLine(“{0} {1} {2}”, a, b, c) 1 2 5
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#
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(“SuOk”)
// 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;
}
TestFunc(a, ref b, out c);
System.Console.WriteLine(“{0} {1} {2}”, a, b, c); // 1 2 5
int Sum(params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}
Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
System.Console.WriteLine(“Greetings, ”
+ prefix + ” ” + name);
}
SayHello(name, “”);
}
Deprecated unstructured error handling
On Error GoTo MyErrorHandler
…
MyErrorHandler: System.Console.WriteLine(Err.Description)
Throw ex
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
Exception up = new Exception(“Something is really wrong.”);
throw up; // ha ha
y = 0;
x = 10 / y;
}
catch (Exception ex) { //Argument is optional, no “When” keyword
Console.WriteLine(ex.Message);
}
finally{
// Do something
}
Namespace ASPAlliance.DotNet.Community
…
End Namespace
Namespace DotNet
Namespace Community
…
End Namespace
End Namespace
End Namespace
namespace ASPAlliance.DotNet.Community {
…
}
namespace DotNet {
namespace Community {
…
}
}
}
Accessibility keywords
Public
Private
Friend
Protected
Protected Friend
Shared
Class Articles
Inherits Authors
…
End Class
Interface IArticle
…
End Interface
Interface IArticle
Inherits IAuthor
…
End Interface
Class PublicationDate
Implements</strong> IArticle, IRating
…
End Class
//Accessibility keywords
public
private
internal
protected
protected internal
static
class Articles: Authors {
…
}
interface IArticle {
…
}
interface IArticle: IAuthor {
…
}
class PublicationDate: IArticle, IRating {
…
}
Class TopAuthor
Private _topAuthor As Integer
_topAuthor = 0
End Sub
Me._topAuthor = topAuthor
End Sub
Desctructor code to free unmanaged resources
MyBase.Finalize()
End Sub
End Class
class TopAuthor {
private int _topAuthor;
_topAuthor = 0;
}
this._topAuthor= topAuthor
}
// Destructor code to free unmanaged resources.
// Implicitly creates a Finalize method
}
}
Dim author As TopAuthor = New TopAuthor
With author
.Name = “Steven”
.AuthorRanking = 3
End With
author.Demote() Calling Shared method
or
TopAuthor.Rank()
author2.Name = “Joe”
System.Console.WriteLine(author2.Name) Prints Joe
author = New TopAuthor
If TypeOf obj Is TopAuthor Then _
System.Console.WriteLine(“Is a TopAuthor object.”)
TopAuthor author = new TopAuthor();
author.Name = “Steven”;
author.AuthorRanking = 3;
TopAuthor.Demote() //Calling static method
author2.Name = “Joe”;
System.Console.WriteLine(author2.Name) //Prints Joe
author = new TopAuthor();
if (obj is TopAuthor)
SystConsole.WriteLine(“Is a TopAuthor object.”);
Structure AuthorRecord
Public name As String
Public rank As Single
Me.name = name
Me.rank = rank
End Sub
End Structure
Dim author2 As AuthorRecord = author
System.Console.WriteLine(author.name) Prints Steven
System.Console.WriteLine(author2.name) Prints Scott
struct AuthorRecord {
public string name;
public float rank;
this.name = name;
this.rank = rank;
}
}
AuthorRecord author2 = author
SystemConsole.WriteLine(author.name); //Prints Steven
System.Console.WriteLine(author2.name); //Prints Scott
Private _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
private int _size;
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}
Delegate Sub MsgArrivedEventHandler(ByVal message
As String)
delegate implicitly
Event MsgArrivedEvent(ByVal message As String)
Wont throw an exception if obj is Nothing
RaiseEvent MsgArrivedEvent(“Test message”)
RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
Dim WithEvents MyButton As Button
MyButton = New Button
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);
(My_MsgArrivedEventCallback);
//Throws exception if obj is null
MsgArrivedEvent(“Test message”);
MsgArrivedEvent -= new MsgArrivedEventHandler
(My_MsgArrivedEventCallback);
MyButton.Click += new System.EventHandler(MyButton_Click);
System.EventArgs e) {
MessageBox.Show(this, “Button was clicked”, “Info”,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Special character constants
vbCrLf, vbCr, vbLf, vbNewLine
vbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
“”
Chr(65) Returns A
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.”)
c = System.Console.Read() Read single char
System.Console.WriteLine(c) Prints 65 if user enters “A”
//Escape sequences
n, r
t
//Returns A – equivalent to Chr(num) in VB
// or
(char) 65
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.”);
System.Console.WriteLine(c);
//Prints 65 if user enters “A”
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 = 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();
c#和vb.net语法对比图_c#教程
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » c#和vb.net语法对比图_c#教程
相关推荐
-      利用c#远程存取access数据库_c#应用
-      c# 3.0新特性系列:隐含类型var_c#教程
-      c#动态生成树型结构的web程序设计_c#应用
-      论c#变得越来越臃肿是不可避免的_c#应用
-      用c#监控并显示cpu状态信息_c#应用
-      c#中实现vb中的createobject方法_c#应用
-      photoshop给花瓶打造彩绘效果_photoshop教程
-      使用c#创建sql server的存储过程_c#应用