这个是原文地址:VB.NET and C# Comparison
正文开始:
Console.Write("What's your name? ")
Dim name As String = Console.ReadLine()
Console.Write("How old are you? ")
Dim age As Integer = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.",name,age)
' or
Console.WriteLine(name & " is " & age & " years old.")
Dim c As Integer
c = Console.Read()' Read single char
Console.WriteLine(c)' Prints 65 if user enters "A"
Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.",age);
// or
Console.WriteLine(name + " is " + age + " years old.");
int c = Console.Read();// Read single char
Console.WriteLine(c);// Prints 65 if user enters "A"
Imports System.IO
' Write out to text file
Dim writer AsStreamWriter= File.CreateText("c:/myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()
' Read all lines from text file
Dim reader AsStreamReader= 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 NewBinaryWriter(File.OpenWrite("c:/myfile.dat"))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()
' Read from binary file
Dim binReader As NewBinaryReader(File.OpenRead("c:/myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()
using System.IO;
// Write out to text file
StreamWriterwriter = File.CreateText("c://myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();
// Read all lines from text file
StreamReaderreader = 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;
BinaryWriterbinWriter = new BinaryWriter(File.OpenWrite("c://myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();
// Read from binary file
BinaryReaderbinReader = new BinaryReader(File.OpenRead("c://myfile.dat"));str = binReader.ReadString();num = binReader.ReadInt32();binReader.Close();
|
|||||||||||
Imports System Namespace Hello Class HelloWorld Overloads Shared SubMain(ByVal args() As String) Dim name As String = "VB.NET" 'See if an argument was passed from the command line If args.Length = 1 Then name = args(0) Console.WriteLine("Hello," & name & "!") End Sub End Class End Namespace |
using System; namespace Hello { public class HelloWorld { public static voidMain(string[] args) { string name = "C#"; // See if an argument was passed from the command line if (args.Length == 1) name = args[0]; Console.WriteLine("Hello," + name + "!"); } } } |
||||||||||
|
|||||||||||
' Single line only REMSingle line only ''' <summary>XML comments</summary> |
// Single line |
||||||||||
|
|||||||||||
Value Types Reference Types Initializing Implicitly Typed Local Variables Type Information Type Conversion / Casting |
Value Types Reference Types Initializing Implicitly Typed Local Variables Type Information Type Conversion / Casting |
||||||||||
|
|||||||||||
ConstMAX_STUDENTSAsInteger = 25 ' Can set to a const or var; may be initialized in a constructor |
constint MAX_STUDENTS = 25; // Can set to a const or var; may be initialized in a constructor |
||||||||||
|
|||||||||||
EnumAction Start [Stop]' Stop is a reserved word Rewind Forward End Enum EnumStatus 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 |
enumAction {Start,Stop,Rewind,Forward}; enumStatus {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 |
||||||||||
|
|||||||||||
Comparison Arithmetic Assignment Bitwise Logical Note:AndAlso and OrElse perform short-circuit logical evaluations String Concatenation |
Comparison Arithmetic Assignment Bitwise Logical Note:&& and || perform short-circuit logical evaluations String Concatenation |
||||||||||
|
|||||||||||
' Ternary/Conditional operator (Iff evaluates 2nd and 3rd expressions) ' One line doesn't require "End If" ' Use : to put two commands on same line ' Preferred ' To break up any long single line use _ 'Ifx > 5Then Select Casecolor' Must be a primitive data type |
// Ternary/Conditional operator if(age < 20) // Multiple statements must be enclosed in {} No need for _ or : since ; is used to terminate each statement.
|
||||||||||
|
|||||||||||
' Array or collection looping ' Breaking out of loops ' Continue to next iteration |
Pre-test Loops: // no "until" keyword
// Array or collection looping
// Continue to next iteration |
||||||||||
|
|||||||||||
Dim nums()As Integer = {1,3}
|
int[]nums = {1,3}; float[,]twoD = new float[rows,cols]; int[][]jagged = new int[3][] { |
||||||||||
|
|||||||||||
' Pass by value (in,default),reference (in/out),and reference (out) 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,and reference (out) void TestFunc(int x,refint y,outint z) { x++; y++; z = 5; } int a = 1,c;// c doesn't need initializing // Accept variable number of arguments int total = Sum(4,1);// returns 10 /* C# 4.0 supports optional parameters. PrevIoUs versions required function overloading. */ SayHello("Strangelove","Dr."); |
||||||||||
|
|||||||||||
Special character constants (all also accessible from ControlChars class) ' String concatenation (use & or +) ' Chars ' No string literal operator ' String comparison ' String matching with Like - Regex is more powerful ' Substring ' Replacement ' Split ' Date to string ' Integer to String ' String to Integer ' Mutable string |
Escape sequences // String concatenation // Chars // String literal // String comparison // String matching - No Like equivalent,use Regex
// Replacement // Split // Date to string // int to string int x = Convert.ToInt32("-5");// x is -5 // Mutable string |
||||||||||
|
|||||||||||
Imports System.Text.RegularExpressions ' Match a string pattern ' Find and remember all matching patterns ' Remeber multiple parts of matched pattern ' Replace all occurrances of a pattern ' Replace matched patterns ' Split a string based on a pattern |
using System.Text.RegularExpressions; // Match a string pattern
// Replace all occurrances of a pattern // Replace matched patterns // Split a string based on a pattern |
||||||||||
|
|||||||||||
' Throw an exception ' Catch an exception ' Deprecated unstructured error handling |
// Throw an exception // Catch an exception |
||||||||||
|
|||||||||||
NamespaceHarding.Compsci.Graphics ' or NamespaceHarding ImportsHarding.Compsci.Graphics |
namespaceHarding.Compsci.Graphics { // or namespaceHarding { usingHarding.Compsci.Graphics; |
||||||||||
|
|||||||||||
Access Modifiers Class Modifiers Method Modifiers ' All members are Shared ' Inheritance ' Interface definition // Extending an interface // Interface implementation |
Access Modifiers Class Modifiers Method Modifiers No Module equivalent - just use static class // Inheritance
// Extending an interface
|
||||||||||
|
|||||||||||
ClassSuperHero Private powerLevel As Integer Public SubNew() powerLevel = 0 End Sub Public SubNew(ByVal powerLevel As Integer) Me.powerLevel = powerLevel End Sub Shared SubNew() ' Shared constructor invoked before 1st instance is created End Sub Protected Overrides SubFinalize() ' Destructor to free unmanaged resources MyBase.Finalize() End Sub End Class |
classSuperHero { |
||||||||||
|
|||||||||||
Dim hero As SuperHero = New SuperHero Withhero hero.Defend("Laura Jones") Dim hero2 As SuperHero = hero' Both reference the same object hero =Nothing' Free the object If heroIsNothingThen _ Dim obj As Object = New SuperHero ' Mark object for quick disposal |
SuperHero hero = new SuperHero(); // No "With" construct hero.Defend("Laura Jones");
hero =null;// Free the object if (hero ==null) Object obj = new SuperHero(); using(StreamReader reader = File.OpenText("test.txt")) { string line; while ((line = reader.ReadLine()) != null) Console.WriteLine(line); } |
||||||||||
|
|||||||||||
StructureStudentRecord Dim stu As StudentRecord = New StudentRecord("Bob",3.5) |
structStudentRecord { 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); |
||||||||||
|
|||||||||||
' Auto-implemented properties are new to VB10 ' Traditional property implementation ' Read-only property ' Write-only property |
// Auto-implemented properties // Traditional property implementation // Read-only property // Write-only property |
||||||||||
|
|||||||||||
DelegateSub MsgArrivedEventHandler(ByVal message As String) EventMsgArrivedEvent As MsgArrivedEventHandler ' or to define an event which declares a delegate implicitly AddHandlerMsgArrivedEvent,AddressOfMy_MsgArrivedCallback Imports System.Windows.Forms DimWithEventsMyButton As Button' WithEvents can't be used on local variable Private Sub MyButton_Click(ByVal sender As System.Object,_ |
delegatevoid MsgArrivedEventHandler(string message); eventMsgArrivedEventHandler MsgArrivedEvent; // Delegates must be used with events in C#
Button MyButton = new Button(); private void MyButton_Click(object sender,System.EventArgs e) { |
||||||||||
|
|||||||||||
' Enforce accepted data type at compile-time ' Subroutine can display any type of List ' Class works on any data type ' Limit T to only types that implement IComparable |
// Enforce accepted data type at compile-time // Function can display any type of List // Class works on any data type // Limit T to only types that implement IComparable |
||||||||||
|
|||||||||||
|
|||||||||||