王朝网络
分享
 
 
 

C#跟VB.net的对比

王朝c#·作者佚名  2006-04-18
宽屏版  字体: |||超大  

相信下面这张图会对你帮助很大.

Comments

VB.NET

'Single line onlyRem Single line only

C#

// Single line/* Multipleline *//// XML comments on single line/** XML comments on multiple lines */

Data Types

VB.NET

'Value TypesBooleanByteChar (example: 'A')Short, Integer, LongSingle, DoubleDecimalDate 'Reference TypesObjectStringDim x As IntegerSystem.Console.WriteLine(x.GetType())System.Console.WriteLine(TypeName(x)) 'Type conversionDim d As Single = 3.5Dim i As Integer = CType (d, Integer)i = CInt (d)i = Int(d)

C#

//Value Typesboolbyte, sbytechar (example: 'A')short, ushort, int, uint, long, ulongfloat, doubledecimalDateTime //Reference Typesobjectstringint x;Console.WriteLine(x.GetType())Console.WriteLine(typeof(int)) //Type conversionfloat d = 3.5;int i = (int) d

Constants

VB.NET

Const MAX_AUTHORS As Integer = 25ReadOnly MIN_RANK As Single = 5.00

C#

const int MAX_AUTHORS = 25;readonly float MIN_RANKING = 5.00;

Enumerations

VB.NET

Enum ActionStart'Stop is a reserved word[Stop]RewindForwardEnd EnumEnum Status Flunk = 50 Pass = 70 Excel = 90End EnumDim a As Action = Action.Stop If a <> Action.Start Then _'Prints 'Stop is 1' System.Console.WriteLine(a.ToString & ' is ' & a)'Prints 70System.Console.WriteLine(Status.Pass)'Prints PassSystem.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 70System.Console.WriteLine((int) Status.Pass); // Prints PassSystem.Console.WriteLine(Status.Pass);

Operators

VB.NET

'Comparison= < > <= >= <> 'Arithmetic+ - * /Mod (integer division)^ (raise to a power) 'Assignment= += -= *= /= = ^= <<= >>= &= 'BitwiseAndAndAlso OrOrElse Not << >> 'LogicalAnd AndAlso OrOrElseNot '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 lineIf x <> 100 And y < 5 Then x *= 5 : y *= 2 'PreferredIf x <> 100 And y < 5 Then x *= 5 y *= 2End If 'or to break up any long single command use _If henYouHaveAReally Lines Then _ UseTheUnderscore(charToBreakItUp) If x > 5 Then x *= y ElseIf x = 5 Then x += y ElseIf x < 10 Then x -= yElse x /= yEnd If 'Must be a primitive data typeSelect Case color Case 'black', 'red' r += 1 Case 'blue' b += 1 Case 'green' g += 1 Case Else other += 1End 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 stringswitch (color){ case 'black': case 'red': r++; break; case 'blue' break; case 'green': g++; break; default: other++; break;}

Loops

VB.NET

'Pre-test Loops:While c < 10 c += 1End While Do Until c = 10 c+= 1Loop 'Post-test Loop:Do While c < 10 c += 1Loop For c = 2 To 10 Step 2 System.Console.WriteLine(c)Next 'Array or collection loopingDim 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) i++;for (i = 2; i < = 10; i += 2) System.Console.WriteLine(i); //Post-test Loop:do i++;while (i < 10);// Array or collection loopingstring[] names = {'Steven', 'SuOk', 'Sarah'};foreach (string s in names) System.Console.WriteLine(s);

Arrays

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 elementsDim names(4) As Stringnames(0) = 'Steven''Throws System.IndexOutOfRangeExceptionnames(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.5Dim jagged()() As Integer = { _ New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }jagged(0)(4) = 5

C#

int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++) Console.WriteLine(nums[i]);// 5 is the size of the arraystring[] names = new string[5];names[0] = 'Steven';// Throws System.IndexOutOfRangeExceptionnames[5] = 'Sarah'// C# can't dynamically resize an array.//Just copy into new array.string[] names2 = new string[7];// or names.CopyTo(names2, 0);Array.Copy(names, names2, names.Length); float[,] twoD = new float[rows, cols];twoD[2,0] = 4.5; int[][] jagged = new int[3][] { new int[5], new int[2], new int[3] };jagged[0][4] = 5;

Functions

VB.NET

'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 = 5End Sub 'c set to zero by defaultDim a = 1, b = 1, c As IntegerTestFunc(a, b, c)System.Console.WriteLine('{0} {1} {2}', a, b, c) '1 2 5 'Accept variable number of argumentsFunction Sum(ByVal ParamArray nums As Integer()) As Integer Sum = 0 For Each i As Integer In nums Sum += i NextEnd Function 'Or use a Return statement like C#Dim total As Integer = Sum(4, 3, 2, 1) 'returns 10 'Optional parameters must be listed last'and must have a default valueSub SayHello(ByVal name As String,Optional ByVal prefix As String = '')System.Console.WriteLine('Greetings, ' & prefix& ' ' & name)End SubSayHello('Steven', 'Dr.')SayHello('SuOk')

C#

// 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 initializingTestFunc(a, ref b, out c);System.Console.WriteLine('{0} {1} {2}', a, b, c); // 1 2 5 // Accept variable number of argumentsint Sum(params int[] nums) { int sum = 0; foreach (int i in nums) sum += i; return sum;} int total = Sum(4, 3, 2, 1); // returns 10 /* C# doesn'tsupport optional arguments/parameters.Just create two different versions of the same function. */void SayHello(string name, string prefix) { System.Console.WriteLine('Greetings, '

+ prefix + ' ' + name);}void SayHello(string name) { SayHello(name, '');}

Exception Handling

VB.NET

'Deprecated unstructured error handlingOn 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 / yCatch 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 NamespaceEnd Namespace Imports ASPAlliance.DotNet.Community

C#

namespace ASPAlliance.DotNet.Community { ...} // or namespace ASPAlliance { namespace DotNet { namespace Community { ... } }} using ASPAlliance.DotNet.Community;

Classes / Interfaces

VB.NET

'Accessibility keywordsPublicPrivateFriendProtectedProtected FriendShared 'InheritanceClass Articles Inherits Authors ...End Class 'Interface definitionInterface IArticle ...End Interface 'Extending an interfaceInterface IArticle Inherits IAuthor ...End Interface 'Interface implementationClass PublicationDate Implements IArticle, IRating ...End Class

C#

//Accessibility keywordspublicprivateinternalprotectedprotected internalstatic //Inheritanceclass Articles: Authors { ...} //Interface definitioninterface IArticle { ...} //Extending an interfaceinterface IArticle: IAuthor { ...} //Interface implementationclass PublicationDate: IArticle, IRating { ...}

Constructors / Destructors

VB.NET

Class TopAuthor Private _topAuthor As Integer Public Sub New() _topAuthor = 0 End Sub Public Sub New(ByVal topAuthor As Integer) Me._topAuthor = topAuthor End Sub Protected Overrides Sub Finalize()'Desctructor code to free unmanaged resources MyBase.Finalize() End SubEnd Class

C#

class TopAuthor { private int _topAuthor; public TopAuthor() {_topAuthor = 0; } public TopAuthor(int topAuthor) { this._topAuthor= topAuthor } ~TopAuthor() { // Destructor code to free unmanaged resources. // Implicitly creates a Finalize method }}

Objects

VB.NET

Dim author As TopAuthor = New TopAuthorWith author .Name = 'Steven' .AuthorRanking = 3End Withauthor.Rank('Scott')author.Demote() 'Calling Shared method'orTopAuthor.Rank() Dim author2 As TopAuthor = author 'Both refer to same objectauthor2.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 TopAuthorIf TypeOf obj Is TopAuthor Then _ System.Console.WriteLine('Is a TopAuthor object.')

C#

TopAuthor author = new TopAuthor();//No 'With' constructauthor.Name = 'Steven';author.AuthorRanking = 3; author.Rank('Scott');TopAuthor.Demote() //Calling static method TopAuthor author2 = author //Both refer to same objectauthor2.Name = 'Joe';System.Console.WriteLine(author2.Name) //Prints Joe author = null //Free the object if (author == null) author = new TopAuthor(); Object obj = new TopAuthor();if (obj is TopAuthor) SystConsole.WriteLine('Is a TopAuthor object.');

Structs

VB.NET

Structure AuthorRecord Public name As String Public rank As Single Public Sub New(ByVal name As String, ByVal rank As Single) Me.name = name Me.rank = rank End SubEnd Structure Dim author As AuthorRecord = New AuthorRecord('Steven', 8.8)Dim author2 As AuthorRecord = authorauthor2.name = 'Scott'System.Console.WriteLine(author.name) 'Prints StevenSystem.Console.WriteLine(author2.name) 'Prints Scott

C#

struct AuthorRecord { public string name; public float rank; public AuthorRecord(string name, float rank) { this.name = name; this.rank = rank; }}AuthorRecord author = new AuthorRecord('Steven', 8.8);AuthorRecord author2 = authorauthor.name = 'Scott';SystemConsole.WriteLine(author.name); //Prints StevenSystem.Console.WriteLine(author2.name); //Prints Scott

Properties

VB.NET

Private _size As IntegerPublic 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 SetEnd Property foo.Size += 1

C#

private int _size;public int Size { get { return _size; } set { if (value < 0) _size = 0; else _size = value; }} foo.Size++;

Delegates / Events

VB.NET

Delegate Sub MsgArrivedEventHandler(ByVal messageAs String) Event MsgArrivedEvent As MsgArrivedEventHandler 'or to define an event which declares a'delegate implicitlyEvent MsgArrivedEvent(ByVal message As String) AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback'Won't throw an exception if obj is NothingRaiseEvent MsgArrivedEvent('Test message')RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallbackImports System.Windows.Forms 'WithEvents can't be used on local variableDim WithEvents MyButton As ButtonMyButton = 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 nullMsgArrivedEvent('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 constantsvbCrLf, vbCr, vbLf, vbNewLinevbNullStringvbTabvbBackvbFormFeedvbVerticalTab''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)'orSystem.Console.WriteLine(name & ' is ' & age & ' years old.')Dim c As Integerc = System.Console.Read() 'Read single charSystem.Console.WriteLine(c) 'Prints 65 if user enters 'A'

C#

//Escape sequencesn, rt Convert.ToChar(65)

//Returns 'A' - equivalent to Chr(num) in VB// or(char) 65 System.Console.Write('What's your name? ');string name = SYstem.Console.ReadLine();System.Console.Write('How old are you? ');int age = Convert.ToInt32(System.Console.ReadLine());System.Console.WriteLine('{0} is {1} years old.',

name, age);//orSystem.Console.WriteLine(name + ' is ' +

age + ' years old.'); int c = System.Console.Read(); //Read single charSystem.Console.WriteLine(c);

//Prints 65 if user enters 'A'

File I/O

VB.NET

Imports System.IO 'Write out to text fileDim writer As StreamWriter = File.CreateText('c:myfile.txt')writer.WriteLine('Out to file.')writer.Close() 'Read all lines from text fileDim 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 Whilereader.Close() 'Write out to binary fileDim str As String = 'Text data'Dim num As Integer = 123Dim binWriter As New BinaryWriter(File.OpenWrite('c:myfile.dat'))binWriter.Write(str)binWriter.Write(num)binWriter.Close() 'Read from binary fileDim binReader As New BinaryReader(File.OpenRead('c:myfile.dat'))str = binReader.ReadString()num = binReader.ReadInt32()binReader.Close()

C#

using System.IO; //Write out to text fileStreamWriter writer = File.CreateText('c:myfile.txt');writer.WriteLine('Out to file.');writer.Close(); //Read all lines from text fileStreamReader 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 filestring 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 fileBinaryReader binReader = new BinaryReader(File.OpenRead('c:myfile.dat'));str = binReader.ReadString();num = binReader.ReadInt32();binReader.Close();

最后更新 ( 2005-03-02 19:10 )

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
>>返回首页<<
推荐阅读
 
 
频道精选
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
© 2005- 王朝网络 版权所有