-
VB与C#的区别(转载)(2)
Dim buffer As New System.Text.StringBuilder("two ")
buffer.Append("three ")
buffer.Insert(0, "one ")
buffer.Replace("two", "TWO")
Console.WriteLine(buffer) ' Prints "one TWO three"Escape sequences
"n, "r
"t
""
""
// String concatenation
string school = "Harding"t";
school = school + "University"; // school is "Harding (tab) University"// Chars
char letter = school[0]; // letter is H
letter = Convert.ToChar(65); // letter is A
letter = (char)65; // same thing
char[] word = school.ToCharArray(); // word holds Harding// String literal
string msg = @"File is c:"temp"x.dat";
// same as
string msg = "File is c:""temp""x.dat";// String comparison
string mascot = "Bisons";
if (mascot == "Bisons") // true
if (mascot.Equals("Bisons")) // true
if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.CompareTo("Bisons") == 0) // trueConsole.WriteLine(mascot.Substring(2, 3)); // Prints "son"
// String matching
// No Like equivalent - use regular expressions
using System.Text.RegularExpressions;
Regex r = new Regex(@"Jo[hH]. "d:*");
if (r.Match("John 3:16").Success) // true// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer); // Prints "one TWO three"
VB.NET
Exception Handling
C#
' Throw an exception
Dim ex As New Exception("Something is really wrong.")
Throw ex' Catch an exception
Try
y = 0
x = 10 / y
Catch ex As Exception When y = 0 ' Argument and When is optional
Console.WriteLine(ex.Message)
Finally
Beep()
End Try' Deprecated unstructured error handling
On Error GoTo MyErrorHandler
...
MyErrorHandler: Console.WriteLine(Err.Description)// Throw an exception
Exception up = new Exception("Something is really wrong.");
throw up; // ha ha// Catch an exception
try {
y = 0;
x = 10 / y;
}
catch (Exception ex) { // Argument is optional, no "When" keyword
Console.WriteLine(ex.Message);
}
finally {
// Requires reference to the Microsoft.VisualBasic.dll
// assembly (pre .NET Framework v2.0)
Microsoft.VisualBasic.Interaction.Beep();
}
VB.NET
Namespaces
C#
Namespace Harding.Compsci.Graphics
...
End Namespace' or
Namespace Harding
Namespace Compsci
Namespace Graphics
...
End Namespace
End Namespace
End NamespaceImports Harding.Compsci.Graphics
namespace Harding.Compsci.Graphics {
...
}// or
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}using Harding.Compsci.Graphics;
VB.NET
Classes / Interfaces
C#
Accessibility keywords
Public
Private
Friend
Protected
Protected Friend
Shared' Inheritance
Class FootballGame
Inherits Competition
...
End Class' Interface definition
Interface IAlarmClock
...
End Interface// Extending an interface
Interface IAlarmClock
Inherits IClock
...
End Interface// Interface implementation
Class WristWatch
Implements IAlarmClock, ITimer
...
End ClassAccessibility keywords
public
private
internal
protected
protected internal
static// Inheritance
class FootballGame : Competition {
...
}
// Interface definition
interface IAlarmClock {
...
}// Extending an interface
interface IAlarmClock : IClock {
...
}
// Interface implementation
class WristWatch : IAlarmClock, ITimer {
...
}
VB.NET
Constructors / Destructors
C#
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 Classclass 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
}
}
VB.NET
Using Objects
C#
Dim hero As SuperHero = New SuperHero
' or
Dim hero As New SuperHeroWith hero
.Name = "SpamMan"
.PowerLevel = 3
End Withhero.Defend("Laura Jones")
hero.Rest() ' Calling Shared method
' or
SuperHero.Rest()Dim hero2 As SuperHero = hero ' Both reference the same object
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name) ' Prints WormWomanhero = Nothing ' Free the object
If hero IsNothing Then _
hero = New SuperHeroDim obj As Object = New SuperHero
If TypeOf obj Is SuperHero Then _
Console.WriteLine("Is a SuperHero object.")' Mark object for quick disposal
Using reader As StreamReader = File.OpenText("test.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = reader.ReadLine()
End While
End UsingSuperHero hero = new SuperHero();
// No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;
hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method
SuperHero hero2 = hero; // Both reference the same object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name); // Prints WormWomanhero = null ; // Free the object
if (hero == null)
hero = new SuperHero();Object obj = new SuperHero();
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");// Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) {
string line;
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
}
VB.NET
Structs
C#
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 StructureDim stu As StudentRecord = New StudentRecord("Bob", 3.5)
Dim stu2 As StudentRecord = stu
stu2.name = "Sue"
Console.WriteLine(stu.name) ' Prints Bob
Console.WriteLine(stu2.name) ' Prints Suestruct 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);
StudentRecord stu2 = stu;
stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue
VB.NET
Properties
C#
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 Propertyfoo.Size += 1
private int _size;
public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}
foo.Size++;
VB.NET
Delegates / Events
C#
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_MsgArrivedCallbackImports System.Windows.Forms
Dim WithEvents MyButton As Button ' WithEvents can't be used on local variable
MyButton = New ButtonPrivate 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 Subdelegate void MsgArrivedEventHandler(string message);
event MsgArrivedEventHandler MsgArrivedEvent;
// Delegates must be used with events in C#
MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message"); // Throws exception if obj is null
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);
}
VB.NET
Console I/O
C#
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.", name, 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"
VB.NET
File I/O
C#
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()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://blog.csdn.net/minsenwu/article/details/7615210