VB.NET | C# | ||||||||||
注释 | |||||||||||
' 仅一行 Rem 仅一行 | // Single line /* Multiple line */ /// XML comments on single line /** XML comments on multiple lines */ | ||||||||||
Data Types数据类型 | |||||||||||
Value Types Boolean Byte Char (example: "A"c) Short, Integer, Long Single, Double Decimal Date 引用类型 Dim x As Integer ' 类型转换 | Value Types bool byte, sbyte char (example: 'A') short, ushort, int, uint, long, ulong float, double decimal DateTime (不是C# 内建类型) 引用类型 int x;
| ||||||||||
Constants | |||||||||||
Const MAX_STUDENTS As Integer = 25 ' Can be set to a const or a variable. May be initialized in a constructor. | const int MAX_STUDENTS = 25; // Can be set to a const or a variable. May be initialized in a constructor. | ||||||||||
Enumerations | |||||||||||
Enum Action Start [Stop] ' Stop is a reserved word 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 _ Console.WriteLine(a.ToString & " is " & a) ' Prints "Stop is 1" Console.WriteLine(Status.Pass) ' Prints 70 Console.WriteLine(Status.Pass.ToString()) ' Prints Pass | enum Action {Start, Stop, Rewind, Forward}; enum Status {Flunk = 50, Pass = 70, Excel = 90}; Action a = Action.Stop; if (a != Action.Start) Console.WriteLine(a + " is " + (int) a); // Prints "Stop is 1" Console.WriteLine((int) Status.Pass); // Prints 70 Console.WriteLine(Status.Pass); // Prints Pass | ||||||||||
Operators | |||||||||||
Comparison = < > <= >= <> Arithmetic Assignment Bitwise Logical Note: AndAlso and OrElse are for short-circuiting logical evaluations String Concatenation | Comparison == < > <= >= != Arithmetic Assignment Bitwise Logical Note: && and || perform short-circuit logical evaluations String Concatenation | ||||||||||
Choices | |||||||||||
greeting = IIf(age < 20, "What's up?", "Hello") ' One line doesn't 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 Select Case color ' Must be a primitive data type | greeting = age < 20 ? "What's up?" : "Hello"; if (x != 100 && y < 5) { // Multiple statements must be enclosed in {} No need for _ or : since ; is used to terminate each statement.
| ||||||||||
Loops | |||||||||||
' Array or collection looping | Pre-test Loops: // no "until" keyword
| ||||||||||
Arrays | |||||||||||
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) = "David" names(5) = "Bobby" ' Throws System.IndexOutOfRangeException ' Resize the array, keeping the existing values (Preserve is optional) ReDim Preserve names(6)
| 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] = "David"; names[5] = "Bobby"; // Throws System.IndexOutOfRangeException // C# can't dynamically resize an array. Just copy into new array. string[] names2 = new string[7]; Array.Copy(names, names2, names.Length); // or names.CopyTo(names2, 0); float[,] twoD = new float[rows, cols]; int[][] jagged = new int[3][] { | ||||||||||
Functions | |||||||||||
' 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 Dim a = 1, b = 1, c As Integer ' c set to zero by default ' Accept variable number of arguments ' Optional parameters must be listed last and must have a default value | // 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 // Accept variable number of arguments int total = Sum(4, 3, 2, 1); // returns 10 /* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */ | ||||||||||
Exception Handling | |||||||||||
' Deprecated unstructured error handling On Error GoTo MyErrorHandler ... MyErrorHandler: Console.WriteLine(Err.Description) Dim ex As New Exception("Something is really wrong.") Throw ex Try | Exception up = new Exception("Something is really wrong."); throw up; // ha ha try { | ||||||||||
Namespaces | |||||||||||
Namespace Harding.Compsci.Graphics ... End Namespace ' or Namespace Harding Imports Harding.Compsci.Graphics | namespace Harding.Compsci.Graphics { ... } // or namespace Harding { using Harding.Compsci.Graphics; | ||||||||||
Classes / Interfaces | |||||||||||
Accessibility keywords Public Private Friend Protected Protected Friend Shared ' Inheritance ' Interface definition // Extending an interface // Interface implementation | Accessibility keywords public private internal protected protected internal static // Inheritance
// Extending an interface
| ||||||||||
Constructors / Destructors | |||||||||||
Class SuperHero Private _powerLevel As Integer Public Sub New() _powerLevel = 0 End Sub Public Sub New(ByVal powerLevel As Integer) Me._powerLevel = powerLevel End Sub Protected Overrides Sub Finalize() ' Desctructor code to free unmanaged resources MyBase.Finalize() End Sub End Class | class SuperHero { private int _powerLevel; public SuperHero() { _powerLevel = 0; } public SuperHero(int powerLevel) { this._powerLevel= powerLevel; } ~SuperHero() { // Destructor code to free unmanaged resources. // Implicitly creates a Finalize method } } | ||||||||||
Objects | |||||||||||
Dim hero As SuperHero = New SuperHero With hero .Name = "SpamMan" .PowerLevel = 3 End With hero.Defend("Laura Jones") hero.Rest() ' Calling Shared method ' or SuperHero.Rest() Dim hero2 As SuperHero = hero ' Both refer to same object hero = Nothing ' Free the object If hero Is Nothing Then _ Dim obj As Object = New SuperHero | SuperHero hero = new SuperHero(); // No "With" construct hero.Name = "SpamMan"; hero.PowerLevel = 3; hero.Defend("Laura Jones");
hero = null ; // Free the object if (hero == null) Object obj = new SuperHero(); | ||||||||||
Structs | |||||||||||
Structure StudentRecord Public name As String Public gpa As Single Public Sub New(ByVal name As String, ByVal gpa As Single) Me.name = name Me.gpa = gpa End Sub End Structure Dim stu As StudentRecord = New StudentRecord("Bob", 3.5) | struct StudentRecord { public string name; public float gpa; public StudentRecord(string name, float gpa) { this.name = name; this.gpa = gpa; } } StudentRecord stu = new StudentRecord("Bob", 3.5f); | ||||||||||
Properties | |||||||||||
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 | private int _size; public int Size { get { return _size; } set { if (value < 0) _size = 0; else _size = value; } }
| ||||||||||
Delegates / Events | |||||||||||
Delegate Sub MsgArrivedEventHandler(ByVal message As String) Event MsgArrivedEvent As MsgArrivedEventHandler ' or to define an event which declares a delegate implicitly AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback Imports System.Windows.Forms Dim WithEvents MyButton As Button ' WithEvents can't be used on local variable Private Sub MyButton_Click(ByVal sender As System.Object, _ | delegate void MsgArrivedEventHandler(string message); event MsgArrivedEventHandler MsgArrivedEvent; // Delegates must be used with events in C#
Button MyButton = new Button(); private void MyButton_Click(object sender, System.EventArgs e) { | ||||||||||
Console I/O | |||||||||||
Special character constants vbCrLf, vbCr, vbLf, vbNewLine vbNullString vbTab vbBack vbFormFeed vbVerticalTab "" Chr(65) ' Returns 'A' Console.Write("What's your name? ") | Escape sequences /n, /r /t // /" Convert.ToChar(65) // Returns 'A' - equivalent to Chr(num) in VB Console.Write("What's your name? ");
| ||||||||||
File I/O | |||||||||||
Imports System.IO ' Write out to text file ' Read all lines from text file ' Write out to binary file ' Read from binary file | using System.IO; // Write out to text file // Read all lines from text file // Write out to binary file // Read from binary file |
VB.NET与 C# 的对照表
最新推荐文章于 2024-06-26 00:31:21 发布