c#和vb.net的语法相差还是比较大的. 可能你会c#,可能你会vb.
将它们俩放在一起对比一下你就会很快读懂,并掌握另一门语言.
相信下面这张图会对你帮助很大.
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 action start 'stop is a reserved word[stop] rewind forwardend 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= += -= *= /= = ^= <<= >>= &= 'bitwiseand andalso or orelse not << >> 'logicaland andalso or orelse not '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 < longline and _ itneedstobebrokeninto2 > 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't support optional arguments/parameters.just create two different versions of the same function. */void sayhello(string name, string prefix) { system.console.writeline("greetings, "
|
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 implementation</span>class publicationdate implements</strong> 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,
|
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)
|
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(); |
新闻热点
疑难解答
图片精选