//z 2012-3-7 13:30:51 PM IS2120@CSDN
|
|||||||||||
Imports System Namespace Hello Class HelloWorld Overloads Shared Sub Main(ByVal args() As String) Dim name As String = "VB.NET" 'See if an argument was passedfrom 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 void Main(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 Nullable Types Implicitly Typed Local Variables Type Information Type Conversion / Casting |
Value Types Reference Types Initializing Nullable Types Implicitly Typed Local Variables Type Information Type Conversion / Casting |
||||||||||
|
|||||||||||
ConstMAX_STUDENTS As Integer = 25 ' Can set to a const orvar; may be initialized in a constructor |
const int MAX_STUDENTS = 25; // Can set to a const or var; may be initialized in a constructor |
||||||||||
|
|||||||||||
Enum Action Start [Stop]' Stopis 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 |
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 |
||||||||||
|
|||||||||||
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 |
||||||||||
|
|||||||||||
' Null-coalescing operator if called with 2 arguments ' Ternary/Conditional operator (IIf evaluates 2nd and 3rd expressions) ' One line doesn't require "End If" ' Use : to put two commands on same line ' Preferred ' Use _ to break up long single line or use implicit line break 'If x > 5 Then Select Case color ' Must be a primitive data type |
// Null-coalescing operator // 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} Dim twoD(rows-1,cols-1) As Single |
int[] nums = {1,3}; float[,] twoD = new float[rows,cols]; int[][] jagged = new int[3][] { |
||||||||||
|
|||||||||||
' Pass by value (in,default),reference (in/out),andreference (out) Dim a = 1,b = 1,c As Integer ' cset to zero by default ' Accept variable number of arguments ' Optional parameters must belisted lastand must have a default value |
// Pass by value (in,andreference (out) void TestFunc(int x,ref int y,out int 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 |
||||||||||
@H_404_1627@ | |||||||||||
VB.NET | Regular Expressions | C# |
Imports System.Text.RegularExpressions
' Match a string pattern
Dim r As New Regex("j[aeIoU]h?. \d:*",RegexOptions.IgnoreCase Or _
RegexOptions.Compiled)
If (r.Match("John 3:16").Success) Then 'true
Console.WriteLine("Match")
End If
' Find and remember all matching patterns
Dim s As String = "My number is 305-1881,not 305-1818."
Dim r As New Regex("(\d+-\d+)")
Dim m As Match = r.Match(s) ' Matches 305-1881 and 305-1818
While m.Success
Console.WriteLine("Found number: " & m.Groups(1).Value & " at position " _
& m.Groups(1).Index.ToString)
m = m.NextMatch()
End While
' Remeber multiple parts of matched pattern
Dim r As New Regex("(\d\d):(\d\d) (am|pm)")
Dim m As Match = r.Match("We left at 03:15 pm.")
If m.Success Then
Console.WriteLine("Hour: " & m.Groups(1).ToString) ' 03
Console.WriteLine("Min: " & m.Groups(2).ToString) ' 15
Console.WriteLine("Ending: " & m.Groups(3).ToString) ' pm
End If
' Replace all occurrances of a pattern
Dim r As New Regex("h\w+?d",RegexOptions.IgnoreCase)
Dim s As String = r.Replace("I heard this was HARD!","easy") ' I easy this was easy!
' Replace matched patterns
Dim s As String = Regex.Replace("123 < 456","(\d+) . (\d+)","$2 > $1")' 456 > 123
' Split a string based on a pattern
Dim names As String = "Michael,Pam"
Dim r As New Regex(",\s*")
Dim parts() As String = r.Split(names) ' One name in each slot
using System.Text.RegularExpressions;
// Match a string pattern
Regex r = new Regex(@"j[aeIoU]h?. \d:*",RegexOptions.IgnoreCase |
RegexOptions.Compiled);
if (r.Match("John 3:16").Success) // true
Console.WriteLine("Match");
// Find and remember all matching patterns
string s = "My number is 305-1881,not 305-1818.";
Regex r = new Regex("(\\d+-\\d+)");
// Matches 305-1881 and 305-1818
for (Match m = r.Match(s); m.Success; m = m.NextMatch())
Console.WriteLine("Found number: " + m.Groups[1] + " at position " +
m.Groups[1].Index);
// Remeber multiple parts of matched pattern
Regex r = new Regex("@(\d\d):(\d\d) (am|pm)");
Match m = r.Match("We left at 03:15 pm.");
if (m.Success) {
Console.WriteLine("Hour: " + m.Groups[1]); // 03
Console.WriteLine("Min: " + m.Groups[2]); // 15
Console.WriteLine("Ending: " + m.Groups[3]); // pm
}
// Replace all occurrances of a pattern
Regex r = new Regex("h\\w+?d",RegexOptions.IgnoreCase);
string s = r.Replace("I heard this was HARD!","easy")); // I easy this was easy!
// Replace matched patterns
string s = Regex.Replace("123 < 456",@"(\d+) . (\d+)","$2 > $1"); // 456 > 123
// Split a string based on a pattern
string names = "Michael,Pam";
Regex r = new Regex(@",\s*");
string[] parts = r.Split(names); // One name in each slot
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 ExceptionWhen 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 {
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 Namespace
Imports Harding.Compsci.Graphics
namespace Harding.Compsci.Graphics {
...
}
// or
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}
using Harding.Compsci.Graphics;
VB.NET | Classes / Interfaces | C# |
Access Modifiers
Public
Private
Friend
Protected
Protected Friend
Class Modifiers
MustInherit
NotInheritable
Method Modifiers
MustOverride
NotInheritable
Shared
Overridable
' All members are Shared
Module
' Partial classes
Partial Class Competition
...
End Class
' Inheritance
ClassFootballGame
Inherits Competition
...
End Class
' Interface definition
Interface IAlarmClock
Sub Ring()
Property TriggerDateTime() As DateTime
End Interface
' Extending an interface
Interface IAlarmClock
Inherits IClock
...
End Interface
' Interface implementation
Class WristWatch
Implements IAlarmClock,ITimer
Public Sub Ring() Implements IAlarmClock.Ring
Console.WriteLine("Wake up!")
End Sub
Public Property TriggerDateTime As DateTime Implements IAlarmClock.TriggerDateTime
...
End Class
Access Modifiers
public
private
internal
protected
protected internal
Class Modifiers
abstract
sealed
static
Method Modifiers
abstract
sealed
static
virtual
No Module equivalent - just use static class
// Partial classes
partial class Competition {
...
}
// Inheritance
classFootballGame : Competition {
...
}
// Interface definition
interface IAlarmClock {
void Ring();
DateTime CurrentDateTime { get; set; }
}
// Extending an interface
interface IAlarmClock : IClock {
...
}
// Interface implementation
class WristWatch : IAlarmClock,ITimer {
public void Ring() {
Console.WriteLine("Wake up!");
}
public DateTime TriggerDateTime { get; set; }
...
}
VB.NET | Constructors / Destructors | C# |
Inherits Person
Private powerLevel As Integer
Private name As String
' Default constructor
Public Sub New()
powerLevel = 0
name = "Super Bison"
End Sub
Public Sub New(ByVal powerLevel As Integer)
Me.New("Super Bison") ' Call other constructor
Me.powerLevel = powerLevel
End Sub
Public Sub New(ByVal name As String)
MyBase.New(name) ' Call base classes' constructor
Me.name = name
End Sub
Shared Sub New()
' Shared constructor invoked before 1st instance is created
End Sub
Protected Overrides Sub Finalize()
' Destructor to free unmanaged resources
MyBase.Finalize()
End Sub
End Class
class SuperHero : Person {
private int powerLevel;
private string name;
// Default constructor
public SuperHero() {
powerLevel = 0;
name = "Super Bison";
}
public SuperHero(int powerLevel)
: this("Super Bison") { // Call other constructor
this.powerLevel = powerLevel;
}
public SuperHero(string name)
: base(name) { // Call base classes' constructor
this.name = name;
}
static SuperHero() {
// Static constructor invoked before 1st instance is created
}
~SuperHero() {
// Destructor implicitly creates a Finalize method
}
}
VB.NET | Using Objects | C# |
Dim hero As SuperHero = New SuperHero
' or
Dim hero As 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 reference the same object
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name) ' Prints WormWoman
hero = Nothing ' Free the object
If hero Is Nothing Then _
hero = New SuperHero
Dim 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 Using
SuperHero hero = new SuperHero();
// No "With" but can use object initializers
SuperHero hero = new SuperHero() { Name = "SpamMan",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 WormWoman
hero = null ; // Free the object
if (hero == null)
hero = new SuperHero();
Object obj = new SuperHero();
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");
using (StreamReader reader = File.OpenText("test.txt")) {
string line;
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
}
VB.NET | Structs | C# |
Structure Student
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 Student = New Student("Bob",3.5)
Dim stu2 As Student = stu
stu2.name = "Sue"
Console.WriteLine(stu.name) ' Prints Bob
Console.WriteLine(stu2.name) ' Prints Sue
public string name;
public float gpa;
public Student(string name,float gpa) {
this.name = name;
this.gpa = gpa;
}
}
Student stu = new Student("Bob",3.5f);
Student stu2 = stu;
stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue
VB.NET | Properties | C# |
' Auto-implemented properties are new to VB10
Public Property Name As String
Public Property Size As Integer = -1 ' Default value,Get and Set both Public
' Traditional property implementation
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
' Read-only property
Private mPowerLevel As Integer
Public ReadOnly Property PowerLevel() As Integer
Get
Return mPowerLevel
End Get
End Property
' Write-only property
Private mHeight As Double
Public WriteOnly Property Height() As Double
Set(ByVal value As Double)
mHeight = If(value < 0,mHeight = 0,mHeight = value)
End Set
End Property
// Auto-implemented properties
public string Name { get; set; }
public int Size { get; protected set; } // Set default value in constructor
// Traditional property implementation
private string name;
public string Name {
get {
return name;
}
set {
name = value;
}
}
// Read-only property
private int powerLevel;
public int PowerLevel {
get {
return powerLevel;
}
}
// Write-only property
private double height;
public double Height {
set {
height = value < 0 ? 0 : value;
}
}
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_MsgArrivedCallback
Imports System.Windows.Forms
Dim WithEvents MyButton As Button ' WithEvents can't be used on local variable
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
delegate 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,
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
VB.NET | Generics | C# |
' Enforce accepted data type at compile-time
Dim numbers As New List(Of Integer)
numbers.Add(2)
numbers.Add(4)
DisplayList(Of Integer)(numbers)
' Subroutine can display any type of List
Sub DisplayList(Of T)(ByVal list As List(Of T))
For Each item As T In list
Console.WriteLine(item)
Next
End Sub
' Class works on any data type
Class SillyList(Of T)
Private list(10) As T
Private rand As New Random
Public Sub Add(ByVal item As T)
list(rand.Next(10)) = item
End Sub
Public Function GetItem() As T
Return list(rand.Next(10))
End Function
End Class
' Limit T to only types that implement IComparable
Function Maximum(Of T As IComparable)(ByVal ParamArray items As T()) As T
Dim max As T = items(0)
For Each item As T In items
If item.CompareTo(max) > 0 Then max = item
Next
Return max
End Function
// Enforce accepted data type at compile-time
List<int> numbers = new List<int>();
numbers.Add(2);
numbers.Add(4);
DisplayList<int>(numbers);
// Function can display any type of List
void DisplayList<T>(List<T> list) {
foreach (T item in list)
Console.WriteLine(item);
}
// Class works on any data type
class SillyList<T> {
private T[] list = new T[10];
private Random rand = new Random();
public void Add(T item) {
list[rand.Next(10)] = item;
}
public T GetItem() {
return list[rand.Next(10)];
}
}
// Limit T to only types that implement IComparable
T Maximum<T>(params T[] items)where T : IComparable<T> {
T max = items[0];
foreach (T item in items)
if (item.CompareTo(max) > 0)
max = item;
return max;
}
VB.NET | LINQ | C# |
Dim nums() As Integer = {5,8,1,6}
' Get all numbers in the array above 4
Dim results = From value In nums
Where value > 4
Select value
Console.WriteLine(results.Count()) ' 3
Console.WriteLine(results.First()) ' 5
Console.WriteLine(results.Last()) ' 6
Console.WriteLine(results.Average()) ' 6.33333
' Displays 5 8 6
For Each n As Integer In results
Console.Write(n & " ")
Next
results = results.Intersect({5,6,7}) ' 5 6
results = results.Concat({5,5}) ' 5 6 5 1 5
results = results.Distinct() ' 5 6 1
Dim Students() As Student = {
New Student With {.Name = "Bob",.GPA = 3.5},
New Student With {.Name = "Sue",.GPA = 4.0},
New Student With {.Name = "Joe",.GPA = 1.9}
}
' Get an ordered list of all students by GPA with GPA >= 3.0
Dim goodStudents = From s In Students
Where s.GPA >= 3.0
Order By s.GPA Descending
Select s
Console.WriteLine(goodStudents.First.Name) ' Sue
// Get all numbers in the array above 4
var results = from value in nums
where value > 4
select value;
Console.WriteLine(results.Count()); // 3
Console.WriteLine(results.First()); // 5
Console.WriteLine(results.Last()); // 6
Console.WriteLine(results.Average()); // 6.33333
// Displays 5 8 6
foreach (int n in results)
Console.Write(n + " ");
results = results.Intersect(new[] {5,7}); // 5 6
results = results.Concat(new[] {5,5}); // 5 6 5 1 5
results = results.Distinct(); // 5 6 1
Student[] Students = {
new Student{ Name = "Bob",GPA = 3.5 },
new Student{ Name = "Sue",GPA = 4.0 },
new Student{ Name = "Joe",GPA = 1.9 }
};
// Get an ordered list of all students by GPA with GPA >= 3.0
var goodStudents = from s in Students
where s.GPA >= 3.0
orderby s.GPA descending
select s;
Console.WriteLine(goodStudents.First().Name); // Sue
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.",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();