C#和vb net的转换.doc_第1页
C#和vb net的转换.doc_第2页
C#和vb net的转换.doc_第3页
C#和vb net的转换.doc_第4页
C#和vb net的转换.doc_第5页
已阅读5页,还剩17页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

今天在看30个学习必须收藏的网站的时候看到了这篇文章,感觉很好,以前都是自己看MSDN然后自己比较,现在又了这个感觉方便多了,很值得收藏!这个是原文地址:VB.NET and C# Comparison正文开始:Program StructureCommentsData TypesConstantsEnumerationsOperatorsChoicesLoopsArraysFunctionsStringsRegular ExpressionsException HandlingNamespacesClasses / InterfacesConstructors / DestructorsUsing ObjectsStructsPropertiesUpdated!Delegates / EventsGenericsNew!Console I/OFile I/OVB.NETProgram StructureC#Imports SystemNamespace Hello Class HelloWorld Overloads Shared SubMain(ByVal args() As String) Dim name As String = VB.NETSee if an argument was passed from the command line If args.Length = 1 Then name = args(0) Console.WriteLine(Hello, & name & !) End Sub End ClassEnd Namespaceusing System;namespace Hello public class HelloWorld public static voidMain(string args) string name = C#;/ See if an argument was passed from the command line if (args.Length = 1) name = args0; Console.WriteLine(Hello, + name + !); VB.NETCommentsC# Single line onlyREMSingle line only XML comments/ Single line/* Multiple line */ XML comments on single line/* XML comments on multiple lines */VB.NETData TypesC#Value TypesBooleanByte, SByteCharShort, UShort, Integer, UInteger, Long, ULongSingle, DoubleDecimalDateReference TypesObjectStringInitializingDim correct As Boolean = TrueDim b As Byte = &H2Ahex or &O52 for octalDim person As Object = NothingDim name As String = DwightDim grade As Char = BcDim today As Date = #12/31/2007 12:15:00 PM#Dim amount As Decimal = 35.99Dim gpa As Single = 2.9!Dim pi As Double = 3.14159265Dim lTotal As Long = 123456LDim sTotal As Short = 123SDim usTotal As UShort = 123USDim uiTotal As UInteger = 123UIDim ulTotal As ULong = 123ULImplicitly Typed Local VariablesDim s = Hello!Dim nums = New Integer() 1, 2, 3Dim hero = New SuperHero With .Name = BatmanType InformationDimxAsIntegerConsole.WriteLine(x.GetType() Prints System.Int32Console.WriteLine(GetType(Integer) Prints System.Int32Console.WriteLine(TypeName(x) Prints IntegerDim c as New CircleIfTypeOfcIsShape Then _ Console.WriteLine(c is a Shape)Type Conversion / CastingDim d As Single = 3.5Dim i As Integer =CType(d, Integer) set to 4 (Bankers rounding)i =CInt(d) same result as CTypei =Int(d) set to 3 (Int function truncates the decimal)Dim o As Object = 2i =DirectCast(o, Integer) Throws InvalidCastException if type cast failsDim s As New ShapeDim c As Circle =TryCast(s, Circle) Returns Nothing if type cast failsValue Typesboolbyte, sbytecharshort, ushort, int, uint, long, ulongfloat, doubledecimalDateTime(not a built-in C# type)Reference TypesobjectstringInitializingbool correct = true;byte b = 0x2A;/ hexobject person = null;string name = Dwight;char grade = B;DateTime today = DateTime.Parse(12/31/2007 12:15:00);decimal amount = 35.99m;float gpa = 2.9f;double pi = 3.14159265;long lTotal = 123456L;short sTotal = 123;ushort usTotal = 123;uint uiTotal = 123;ulong ulTotal = 123;Implicitly Typed Local Variablesvar s = Hello!;var nums = new int 1, 2, 3 ;var hero = new SuperHero() Name = Batman ;Type Informationint x;Console.WriteLine(x.GetType();/ Prints System.Int32Console.WriteLine(typeof(int);/ Prints System.Int32Console.WriteLine(x.GetType().Name);/ prints Int32Circle c = new Circle();if (cisShape) Console.WriteLine(c is a Shape);Type Conversion / Castingfloat d = 3.5f;i =Convert.ToInt32(d);/ Set to 4 (rounds)int i =(int)d;/ set to 3 (truncates decimal)object o = 2;int i = (int)o;/ Throws InvalidCastException if type cast failsShape s = new Shape();Circle c = sasCircle;/ Returns null if type cast failsVB.NETConstantsC#ConstMAX_STUDENTSAsInteger = 25 Can set to a const or var; may be initialized in a constructorReadOnlyMIN_DIAMETERAsSingle = 4.93constint MAX_STUDENTS = 25;/ Can set to a const or var; may be initialized in a constructorreadonlyfloat MIN_DIAMETER = 4.93f;VB.NETEnumerationsC#EnumAction Start Stop Stop is a reserved word Rewind ForwardEnd EnumEnumStatus Flunk = 50 Pass = 70 Excel = 90End EnumDim a As Action = Action.StopIf a Action.Start Then _ Console.WriteLine(a.ToString & is & a) Prints Stop is 1Console.WriteLine(Status.Pass) Prints 70Console.WriteLine(Status.Pass.ToString() Prints PassenumAction Start, Stop, Rewind, Forward;enumStatus Flunk = 50, Pass = 70, Excel = 90;Action a = Action.Stop;if (a != Action.Start) Console.WriteLine(a + is + (int) a);/ Prints Stop is 1Console.WriteLine(int) Status.Pass);/ Prints 70Console.WriteLine(Status.Pass);/ Prints PassVB.NETOperatorsC#Comparison= = Arithmetic+ - * /Mod(integer division)(raise to a power)Assignment= += -= *= /= = = = &=BitwiseAnd Or Xor Not LogicalAndAlso OrElse And Or Xor NotNote:AndAlso and OrElse perform short-circuit logical evaluationsString Concatenation&Comparison= = !=Arithmetic+ - * /%(mod)/(integer division if both operands are ints)Math.Pow(x, y)Assignment= += -= *= /= %= &= |= = = + -Bitwise& | Logical& | & | !Note:& and | perform short-circuit logical evaluationsString Concatenation+VB.NETChoicesC# Ternary/Conditional operator (Iff evaluates 2nd and 3rd expressions)greeting =If(age 20, Whats up?, Hello) One line doesnt require End IfIfage 20Thengreeting = Whats up?Ifage 20Thengreeting = Whats up?Elsegreeting = Hello Use : to put two commands on same lineIfx 100 AndAlso y 5Thenx *= 5:y *= 2 PreferredIfx 100 AndAlso y 5Then x *= 5 y *= 2End If To break up any long single line use _IfwhenYouHaveAReally LinesThen_ UseTheUnderscore(charToBreakItUp)Ifx 5Then x *= yElseIfx = 5 OrElse y Mod 2 = 0Then x += yElseIfx 10Then x -= yElse x /= yEnd IfSelect Casecolor Must be a primitive data typeCasepink, red r += 1Caseblue b += 1Casegreen g += 1Case Else other += 1End Select/ Ternary/Conditional operatorgreeting = age 20?Whats up?:Hello;if(age 20) greeting = Whats up?;else greeting = Hello;/ Multiple statements must be enclosed in if(x != 100 & y 5) x *= y;elseif (x = 5 | y % 2 = 0) x += y;elseif (x 10) x -= y;else x /= y;/ Every case must end with break or goto caseswitch(color) / Must be integer or stringcasepink:casered: r+;break; caseblue: b+;break; casegreen: g+;break; default: other+;break;/ break necessary on defaultVB.NETLoopsC#Pre-test Loops:Whilec 10 c += 1End WhileDo Untilc = 10 c += 1LoopDo Whilec 10 c += 1LoopForc = 2To10Step2 Console.WriteLine(c)NextPost-test Loops:Do c += 1Loop Whilec 10Do c += 1Loop Untilc = 10 Array or collection loopingDim names As String() = Fred, Sue, BarneyFor Eachs As StringInnames Console.WriteLine(s)Next Breaking out of loopsDim i As Integer = 0While (True) If (i = 5) ThenExit While i += 1End While Continue to next iterationFor i = 0 To 4 If i 4 ThenContinue For Console.WriteLine(i) Only prints 4NextPre-test Loops:/ no until keywordwhile(c 10) c+;for(c = 2; c = 10; c += 2) Console.WriteLine(c);Post-test Loop:do c+;while(c 10);/ Array or collection loopingstring names = Fred, Sue, Barney;foreach(string sinnames) Console.WriteLine(s);/ Breaking out of loopsint i = 0;while (true) if (i = 5)break; i+;/ Continue to next iterationfor (i = 0; i 5; i+) if (i 4)continue; Console.WriteLine(i);/ Only prints 4VB.NETArraysC#Dim nums()As Integer = 1, 2, 3For 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) = Davidnames(5) = Bobby Throws System.IndexOutOfRangeException Resize the array, keeping the existing values (Preserve is optional)ReDim Preservenames(6)Dim twoD(rows-1, cols-1) As SingletwoD(2, 0) = 4.5Dim jagged()()As Integer = _ New Integer(4) , New Integer(1) , New Integer(2) jagged(0)(4) = 5intnums = 1, 2, 3;for (int i = 0; i nums.Length; i+) Console.WriteLine(numsi);/ 5 is the size of the arraystring names = new string5;names0 = David;names5 = Bobby;/ Throws System.IndexOutOfRangeException/ C# cant dynamically resize an array. Just copy into new array.string names2 = new string7;Array.Copy(names, names2, names.Length);/ or names.CopyTo(names2, 0);float,twoD = new floatrows, cols;twoD2,0 = 4.5f;intjagged = new int3 new int5, new int2, new int3 ;jagged04 = 5;VB.NETFunctionsC# Pass by value (in, default), reference (in/out), and reference (out)SubTestFunc(ByValx As Integer,ByRefy As Integer,ByRefz As Integer) x += 1 y += 1 z = 5End SubDim a = 1, b = 1, c As Integer c set to zero by defaultTestFunc(a, b, c)Console.WriteLine(0 1 2, a, b, c) 1 2 5 Accept variable number of argumentsFunctionSum(ByValParamArraynumsAsInteger() As Integer Sum = 0 For Each i As Integer In nums Sum += i NextEnd Function Or use 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 valueSubSayHello(ByVal name As String,OptionalByVal prefix As String = ) Console.WriteLine(Greetings, & prefix & & name)End SubSayHello(Strangelove, Dr.)SayHello(Mom)/ Pass by value (in, default), reference (in/out), and reference (out)void TestFunc(int x,refint y,outint z) x+; y+; z = 5;int a = 1, b = 1, c;/ c doesnt need initializingTestFunc(a,refb,outc);Console.WriteLine(0 1 2, a, b, c);/ 1 2 5/ Accept variable number of argumentsint Sum(paramsint nums) int sum = 0; foreach (int i in nums) sum += i; return sum;int total = Sum(4, 3, 2, 1);/ returns 10/* C# 4.0 supports optional parameters. Previous versions required function overloading. */void SayHello(string name, string prefix = ) Console.WriteLine(Greetings, + prefix + + name);SayHello(Strangelove, Dr.);SayHello(Mom);VB.NETStringsC#Special character constants (all also accessible from ControlChars class)vbCrLf, vbCr, vbLf, vbNewLinevbNullStringvbTabvbBackvbFormFeedvbVerticalTab String concatenation (use & or +)Dim school As String = Harding&vbTabschool = school & University school is Harding (tab) University CharsDim letter AsChar= school.Chars(0) letter is Hletter = Zc letter is Zletter = Convert.ToChar(65) letter is Aletter =Chr(65) same thingDim word() As Char = school.ToCharArray() word holds Harding No string literal operatorDim msg As String = File is c:tempx.dat String comparisonDim mascot As String = BisonsIf (mascot = Bisons) Then trueIf (mascot.Equals(Bisons) Then trueIf (mascot.ToUpper().Equals(BISONS) Then trueIf (mascot.CompareTo(Bisons) = 0) Then true String matching with Like - Regex is more powerfulIf (John 3:16LikeJoHh? #:*) Thentrue Substrings = mascot.Substring(2, 3) s is son Replacements = mascot.Replace(sons, nomial) s is Binomial SplitDim names As String = Michael,Dwight,Jim,PamDim parts() As String = names.Split(,.ToCharArray() One name in each slot Date to stringDim dt As New DateTime(1973, 10, 12)Dim s As String = My birthday: & dt.ToString(MMM dd, yyyy) Oct 12, 1973 Integer to StringDim x As Integer = 2Dim y As String = x.ToString() y is 2 String to IntegerDim x As Integer = Convert.ToInt32(-5) x is -5 Mutable stringDim buffer As New System.Text.StringBuilder(two )buffer.Append(three )buffer.Insert(0, one )buffer.Replace(two, TWO)Console.WriteLine(buffer) Prints one TWO threeEscape sequencesr/ carriage-returnn/ line-feedt/ tab/ backslash/ quote/ String concatenationstringschool = Hardingt;school = school + University;/ school is Harding (tab) University/ Charscharletter = school0;/ letter is Hletter = Z;/ letter is Zletter = Convert.ToChar(65);/ letter is Aletter =(char)65;/ same thingcharword = school.ToCharArray();/ word holds Harding/ String literalstring msg =File is c:tempx.dat;/ same asstring msg = File is c:tempx.dat;/ String comparisonstring mascot = Bisons;if (mascot = Bisons)/ trueif (mascot.Equals(Bisons)/ trueif (mascot.ToUpper().Equals(BISONS)/ trueif (mascot.CompareTo(Bisons) = 0)/ true/ String matching - No Like equivalent, use Regex/ Substrings = mascot.Substring(2, 3)/ s is son/ Replacements = mascot.Replace(sons, nomial)/ s is Binomial/ Splitstring names = Michael,Dwight,Jim,Pam;string parts = names.Split(,.ToCharArray();/ One name in each slot/ Date to stringDateTime dt = new DateTime(1973, 10, 12);string s = dt.ToString(MMM dd, yyyy);/ Oct 12, 1973/ int to stringint x = 2;string y = x.ToString();/ y is 2/ string to intint x = Convert.ToInt32(-5);/ x is -5/ Mutable stringSystem.Text.StringBuilderbuffer = new System.Text.StringBuilder(two );buffer.Append(three );buffer.Insert(0, one );buffer.Replace(two, TWO);Console.WriteLine(buffer);/ Prints one TWO threeVB.NETRegular ExpressionsC#Imports System.Text.RegularExpressions Match a string patternDim r As NewRegex(jaeiouh?. d:*, RegexOptions.IgnoreCase Or _ RegexOptions.Compiled)If (r.Match(John 3:16).Success) Thentrue Console.WriteLine(Match)End If Find and remember all matching patternsDim s As String = My number is 305-1881, not 305-1818.Dim r As New Regex(d+-d+)Dim m AsMatch= r.Match(s) Matches 305-1881 and 305-1818While 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 patternDim r As New Regex(dd):(dd) (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) pmEnd If Replace all occurrances of a patternDim r As New Regex(hw+?d, RegexOptions.IgnoreCase)Dim s As String = r.Replace(I heard this was HARD!, easy) I easy this was easy! Replace matched patternsDim s As String = Regex.Replace(123 $1) 456 123 Split a string based on a patternDim names As String = Michael, Dwight, Jim, PamDim r As New Regex(,s*)Dim parts() As String = r.Split(names) One name in each slotusing System.Text.RegularExpressions;/ Match a string patternRegexr = newRegex(jaeiouh?. d:*, RegexOptions.IgnoreCase | RegexOptions.Compiled);if (r.Match(John 3:16).Success)/ true Console.WriteLine(Match);/ Find and remember all matching patternsstring s = My number is 305-1881, not 305-1818.;Regex r = new Regex(d+-d+);/ Matches 305-1881 and 305-1818for (Matchm = r.Match(s); m.Success; m = m.NextMatch() Console.WriteLine(Found number: + m.Groups1 + at position + m.Groups1.Index);/ Remeber multiple parts of matched patternRegex r = new Regex(dd):(dd) (am|pm);Match m = r.Match(We left at 03:15 pm.);if (m.Success) Console.WriteLine(Hour: + m.Groups1);/ 03 Co

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论