Comments | |
VB.NET 'Single line only Rem Single line only | C# // Single line |
数据类型 | |
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 |
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); |
操作符 | |
VB.NET 'Comparison
= < > <= >= <>
'Arithmetic
+ - * /
Mod
(integer division)
^ (raise to a power)
'Assignment
= += -= *= /= = ^= <<= >>= &=
'Bitwise
And AndAlso Or OrElse Not << >>
'Logical
And AndAlso Or OrElse Not
'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; } |
循环语句 | |
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)
|
数组 | |
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}; |
函数 | |
VB.NET 'Pass by value (in, default), reference | C# #/ Pass by value (in, default), reference |
错误挂起 | |
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 { |
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 | C# class TopAuthor { |
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(); |
Structs 结构 | |
VB.NET Structure AuthorRecord | C# struct AuthorRecord {
|
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; |
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 |
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; |