|
本帖最后由 lyx199285 于 2014-2-24 13:14 编辑
由于接下来学习的是用C#,语法变化比较大..。我就找了个简单语法介绍的,希望大家能比较快接受..。
原来地址:http://www.studycs.com/html/512.html
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 Loopo 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);// 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, "
+ 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; |
|
评分
-
查看全部评分
|