版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、c# 和 vb.net 的语法相差还是比较大的.可能你会 c#,可能你会 vb.将它们俩放在一起对比一下你就会很快读懂, 并掌握另一门语言.相信下面这张图会对你帮助很大.commentsvb.netsinglelineonlyremsinglelineonlyc#/singleline/*multipleline*/xmlcomments on singleline/*xmlcommentson multiplelines*/data typesvb.netvaluetypesbooleanbytechar (example:a)short,integer,longsingle,doubled
2、ecimaldatereferencetypesobjectstringc#/valuetypesboolbyte,sbytechar (example:a)short,ushort,int,uint,long, ulongfloat,doubledecimaldatetime/referencetypesobjectstringdim x as integersystem.console.writeline(x.gettype()system.console.writeline(typename(x)typeconversiondim d as single= 3.5dim ias inte
3、ger= ctype (d,integer)i= cint(d)i= int(d)intx;console.writeline(x.gettype()console.writeline(typeof(int)/typeconversionfloatd = 3.5;inti= (int)dconstantsvb.netconst max_authorsas integer= 25readonly min_rank as single= 5.00c#constintmax_authors= 25;readonlyfloatmin_ranking = 5.00;enumerationsvb.nete
4、numactionstartstopisa reservedwordstoprewindforwardend enumenumstatusflunk = 50c#enumactionstart,stop,rewind,forward;enumstatusflunk= 50, pass = 70,excel = 90;pass = 70excel = 90end enumdim a as action= action.stopifa action.startthen _printsstopis1system.console.writeline(a.tostring& is & a
5、)prints70system.console.writeline(status.pass)printspasssystem.console.writeline(status.pass.tostring()actiona = action.stop;if(a != action.start)/printsstopis1system.console.writeline(a+ is + (int)a);/prints70system.console.writeline(int)status.pass);/printspasssystem.console.writeline(status.pass)
6、;operatorsvb.netcomparison=arithmetic+-*/mod(integerdivision)(raiseto a power)assignment=+=-=*=/=c#/comparison=!=/arithmetic+-*/%(mod)/(integerdivisionifbothoperands are ints)math.pow(x,y)/assignment=&=bitwiseandandalsoororelsenotlogicalandandalsoororelsenotstringconcatenation&=+=-=*=/=%=&am
7、p;=|=+-/bitwise&|/logical&|!/stringconcatenation+choicesvb.netgreeting= iif(age 20, whatsup?,hello)one linedoesntrequireendif,no elseiflanguage = vb.net thenlangtype = verboseuse:to put two commandson samelineifx 100 and y 5 then x *= 5 :y *= 2c#greeting= age 20 ? whatsup? :hello;if(x != 100
8、 & y 5)preferredifx 100 and y 5 thenx *= 5y *= 2end iforto break up any longsinglecommanduse _ifhenyouhaveareally linesthen _usetheunderscore(chartobreakitup)ifx 5 thenx *= yelseifx = 5 thenx += yelseifx 5)x *= y;elseif(x = 5)x += y;elseif(x 10)x -= y;elsex /= y;/mustbe integeror stringswitch(co
9、lor)case black:case red:r+;break;case bluebreak;case green:g+;case black,redr += 1case blueb += 1case greeng += 1case elseother+= 1end selectbreak;default:other+;break;loopsvb.netpre-testloops:while c 10c += 1end while do untilc = 10c+= 1looppost-testloop:do while c 10c += 1loopfor c = 2 to 10 step
10、2system.console.writeline(c)nextarrayor collectionloopingc#/pre-testloops: while(i 10)i+;for(i= 2; i = 10; i+= 2)system.console.writeline(i);/post-testloop:doi+;while(i 10);dim namesas string()= steven,suok,sarahfor each s as stringin namessystem.console.writeline(s)next/arrayor collectionloopingstr
11、ingnames = steven,suok,sarah;foreach(strings innames)system.console.writeline(s);arraysvb.netdim nums() as integer= 1,2, 3for i asinteger= 0 to nums.length- 1console.writeline(nums(i)next4isthe indexof the lastelement,so itholds5 elementsdim names(4) as stringnames(0) = steventhrowssystem.indexoutof
12、rangeexceptionnames(5) = sarahresizethe array,keeping theexistingvalues(preserveisoptional)redimpreservenames(6)c#intnums = 1,2, 3;for(inti = 0; i nums.length; i+)console.writeline(numsi);/5 isthe sizeof the arraystringnames = new string5;names0 = steven;/throwssystem.indexoutofrangeexceptionnames5
13、= sarah/c# cantdynamicallyresizeanarray./justcopy intonew array.stringnames2= new string7;/or names.copyto(names2, 0);array.copy(names,names2,names.length);float,twod = new floatrows,dimtwod(rows-1,cols-1)as singletwod(2,0) = 4.5dim jagged()()as integer= _newinteger(4),newinteger(1),newinteger(2) ja
14、gged(0)(4)= 5cols;twod2,0= 4.5;intjagged = new int3new int5,new int2,newint3;jagged04= 5;functionsvb.netpassby value(in,default),reference(in/out),and reference(out)sub testfunc(byvalx as integer,byref y as integer,byref z as integer)x += 1y += 1z = 5end subcsetto zero by defaultdim a = 1, b = 1, c
15、as integertestfunc(a,b, c)system.console.writeline(012,a, b, c) 12 5acceptvariablenumber ofargumentsc#/pass by value(in,default),reference/(in/out),and reference(out)voidtestfunc(intx,refinty,outintz) x+;y+;z = 5;inta = 1, b = 1, c; /c doesntneedinitializingtestfunc(a,refb, out c);system.console.wri
16、teline(012,a, b, c);/1 2 5/accept variablenumber ofargumentsfunctionsum(byval paramarraynums as integer()as integersum= 0for each ias integerin numssum+= inextend functionoruse a returnstatementlikec#dimtotalas integer= sum(4, 3, 2,1) returns10optionalparametersmust belistedlastandmust have a defaul
17、tvaluesubsayhello(byvalnameas string,optionalbyval prefixas string=)system.console.writeline(greetings, & prefix& & name)end subsayhello(steven,dr.)sayhello(suok)intsum(params intnums) intsum = 0;foreach(intiinnums)sum += i;returnsum;int total=sum(4, 3, 2, 1); / returns10/*c# doesntsuppo
18、rtoptionalarguments/parameters.just create two differentversionsofthe same function.*/voidsayhello(stringname, stringprefix)system.console.writeline(greetings, + prefix+ + name);voidsayhello(stringname) sayhello(name,);exceptionhandlingvb.netdeprecatedunstructurederrorhandlingc#on errorgoto myerrorh
19、andler.myerrorhandler:system.console.writeline(err.description)dimex as newexception(somethinghas reallygone wrong.)throw extryy = 0 x = 10 / ycatch ex as exceptionwheny = 0argumentand whenisoptionalsystem.console.writeline(ex.message)finallydosomething()end tryexceptionup = newexception(somethingis
20、reallywrong.);throw up; /ha hatryy = 0;x = 10 /y;catch (exceptionex) /argumentisoptional,no when keywordconsole.writeline(ex.message);finally/do somethingnamespacesvb.netnamespaceaspalliance.dotnet.community.end namespaceorc#namespaceaspalliance.dotnet.community./ornamespaceaspalliancenamespacedotne
21、tnamespacecommunity.end namespaceend namespaceend namespaceimportsaspalliance.dotnet.communitynamespaceaspalliancenamespacedotnet namespace community .usingaspalliance.dotnet.community;classes/ interfacesvb.netaccessibilitykeywordspublicprivatefriendprotectedprotectedfriendsharedinheritanceclass art
22、iclesinheritsauthors.end classinterfacedefinitioninterfaceiarticle.c#/accessibilitykeywordspublicprivateinternalprotectedprotectedinternalstatic/inheritanceclassarticles:authors./interfacedefinitioninterfaceiarticle.end interfaceextendingan interfaceinterfaceiarticleinheritsiauthor.end interfaceinte
23、rfaceimplementationclass publicationdateimplementsiarticle,irating.end class/extendingan interfaceinterfaceiarticle:iauthor./interfaceimplementationclasspublicationdate:iarticle,irating.constructors/ destructorsvb.netclass topauthorprivate_topauthoras integerpublicsub new()_topauthor= 0end subpublic
24、sub new(byval topauthoras integer)me._topauthor= topauthorend subprotectedoverridessubfinalize()c#classtopauthor privateint_topauthor;publictopauthor()_topauthor= 0;publictopauthor(inttopauthor)this._topauthor=topauthortopauthor()/destructorcode to freeunmanagedresources.desctructorcode to freeunman
25、agedresourcesmybase.finalize()end subend class/implicitlycreatesafinalizemethodobjectsvb.netdim authoras topauthor = newtopauthorwith author.name = steven.authorranking= 3end withauthor.rank(scott)author.demote()callingsharedmethodortopauthor.rank()dim author2as topauthor = authorbothreferto same ob
26、jectauthor2.name = joesystem.console.writeline(author2.name) printsjoeauthor= nothing freethe objectifauthorisnothingthen _c#topauthor author= new topauthor();/nowithconstructauthor.name = steven;author.authorranking= 3;author.rank(scott);topauthor.demote()/callingstaticmethodtopauthor author2= auth
27、or/bothreferto same objectauthor2.name = joe;system.console.writeline(author2.name) /printsjoeauthor= null/freethe objectif(author= null)author= newtopauthordim obj as object= newtopauthoriftypeof obj is topauthor then _system.console.writeline(isa topauthor object.)author= new topauthor();objectobj
28、= new topauthor();if(objistopauthor)systconsole.writeline(isatopauthor object.);structsvb.netstructureauthorrecordpublicnameas stringpublicrank as singlepublicsub new(byval nameasstring,byval rank as single)m= nameme.rank = rankend subend structuredim authoras authorrecord = newauthorrecord(st
29、even,8.8)dim author2as authorrecord== scottsystem.console.writeline() printsstevensystem.console.writeline() printsscottc#structauthorrecordpublicstringname;publicfloatrank;publicauthorrecord(stringname,floatrank)= name;this.rank= rank;authorrecord a
30、uthor= newauthorrecord(steven,8.8);authorrecord author2= = scott;systemconsole.writeline();/printsstevensystem.console.writeline(); /printsscottpropertiesvb.netprivate_sizeas integerpublicpropertysize()as integergetreturn _sizeend getset (byvalvalue as integer
31、)ifvalue 0 then_size= 0else_size= valueend ifend setend propertyfoo.size+= 1c#privateint_size;publicintsize get return_size;set if(value 0)_size= 0;else_size= value;foo.size+;delegates/eventsvb.netdelegatesubmsgarrivedeventhandler(byvalmessageas string)event msgarrivedeventasmsgarrivedeventhandlerc#
32、delegatevoidmsgarrivedeventhandler(stringmessage);event msgarrivedeventhandlermsgarrivedevent;orto definean event whichdeclaresadelegateimplicitlyevent msgarrivedevent(byvalmessage as string)addhandler msgarrivedevent,addressof my_msgarrivedcallbackwontthrow an exceptionifobj isnothingraiseeventmsga
33、rrivedevent(testmessage)removehandler msgarrivedevent,addressof my_msgarrivedcallbackimportssystem.windows.formswitheventscantbe used on localvariabledim withevents mybutton as buttonmybutton = newbuttonprivatesub mybutton_click(byvalsender as system.object,_byval e as system.eventargs)handles mybut
34、ton.clickmessagebox.show(me,button/delegatesmust be used with eventsinc#msgarrivedevent+= newmsgarrivedeventhandler(my_msgarrivedeventcallback);/throwsexceptionifobjisnullmsgarrivedevent(testmessage);msgarrivedevent-= newmsgarrivedeventhandler(my_msgarrivedeventcallback);usingsystem.windows.forms;bu
35、ttonmybutton = new button();mybutton.click+= newsystem.eventhandler(mybutton_click);privatevoidmybutton_click(objectsender,system.eventargse) messagebox.show(this,button wasclicked,info,messageboxbuttons.ok,messageboxicon.information);was clicked,info,_messageboxbuttons.ok,messageboxicon.information
36、)end subconsole i/ovb.netspecialcharacterconstantsvbcrlf,vbcr,vblf,vbnewlinevbnullstringvbtabvbbackvbformfeedvbverticaltabchr(65)returnsasystem.console.write(whatsyour name?)dim nameas string=system.console.readline()system.console.write(howold areyou? )dim age as integer=val(system.console.readline
37、()system.console.writeline(0is1years old.,name, age)orsystem.console.writeline(name& is & age & years old.)dim c as integerc#/escapesequencesn, rtconvert.tochar(65)/returnsa- equivalenttochr(num) invb/or(char)65system.console.write(whatsyourname?);stringname =system.console.readline();sy
38、stem.console.write(howold areyou? );intage =convert.toint32(system.console.readline();system.console.writeline(0is 1years old.,name, age);c = system.console.read()readsinglecharsystem.console.writeline(c)prints65 ifuser entersa/orsystem.console.writeline(name+ is +age + years old.);int c = system.console.read();/readsinglecharsystem.console.writeline(c);/prints65 ifuser entersafilei/ovb.netimportssystem.iowriteout to textfiledim writeras streamwriter=
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 建筑节能工程热工性能检测报告编制方法选择
- 200吨转炉课程设计
- 数据统计与医院智慧化管理
- 幼儿园急救知识
- 《网络游戏风险控制管理指南》
- 机场设计与规划
- 环境艺术设计职业规划
- 数字字体设计
- 旅游项目设计
- 产品研发设计全流程解析
- 小升初小学数学《找规律》大题量练习总复习试卷练习题一
- 2026年北京市西城区初三下学期二模语文试卷及答案
- 非结核分枝杆菌肺病诊疗专家共识(2026版)
- 北京市海淀区2026届高三高考二模语文试卷(含答案)
- 2026年食品安全管理员资格考试试题【带答案】
- 2026年4月自考13000英语(专升本)试题及答案
- 2026年国家电网中级职称考试(政工专业)综合试题及答案
- 2026中国武夷实业股份有限公司招聘笔试历年参考题库附带答案详解
- 2026年融资专员考核笔题库及完整答案详解(夺冠)
- 2026年哈尔滨市道里区中考一模物理试卷和答案
- 民俗文化融入幼儿园课程的实践研究
评论
0/150
提交评论