VB和c#語法對比


 

  1. VB.NET
  2. 'Single line only
  3. Rem Single line only
  4.  C#
  5. // Single line
  6. /* Multiple
  7. line */
  8. /// XML comments on single line
  9. /** XML comments on multiple lines */
  10. Data Types
  11. VB.NET
  12. 'Value Types
  13. Boolean
  14. Byte
  15. Char (example: "A")
  16. Short, Integer, Long
  17. Single, Double
  18. Decimal
  19. Date 
  20. 'Reference Types
  21. Object
  22. String
  23. Dim x As Integer
  24. System.Console.WriteLine(x.GetType())
  25. System.Console.WriteLine(TypeName(x)) 
  26. 'Type conversion
  27. Dim d As Single = 3.5
  28. Dim i As Integer = CType (d, Integer)
  29. i = CInt (d)
  30. i = Int(d)
  31.  C#
  32. //Value Types
  33. bool
  34. bytesbyte
  35. char (example: 'A')
  36. shortushortintuintlongulong
  37. floatdouble
  38. decimal
  39. DateTime 
  40. //Reference Types
  41. object
  42. string
  43. int x;
  44. Console.WriteLine(x.GetType())
  45. Console.WriteLine(typeof(int)) 
  46. //Type conversion
  47. float d = 3.5;
  48. int i = (int) d
  49. Constants
  50. VB.NET
  51. Const MAX_AUTHORS As Integer = 25
  52. ReadOnly MIN_RANK As Single = 5.00
  53.  C#
  54. const int MAX_AUTHORS = 25;
  55. readonly float MIN_RANKING = 5.00;
  56. Enumerations
  57. VB.NET
  58. Enum Action
  59.   Start
  60.   'Stop is a reserved word
  61. [Stop]
  62.   Rewind
  63.   Forward
  64. End Enum
  65. Enum Status
  66.    Flunk = 50
  67.    Pass = 70
  68.    Excel = 90
  69. End Enum
  70. Dim a As Action = Action.Stop 
  71. If a <> Action.Start Then _
  72. 'Prints "Stop is 1" 
  73.    System.Console.WriteLine(a.ToString & " is " & a)
  74. 'Prints 70
  75. System.Console.WriteLine(Status.Pass)
  76. 'Prints Pass
  77. System.Console.WriteLine(Status.Pass.ToString())
  78.  C#
  79. enum Action {Start, Stop, Rewind, Forward};
  80. enum Status {Flunk = 50, Pass = 70, Excel = 90};
  81. Action a = Action.Stop;
  82. if (a != Action.Start)
  83. //Prints "Stop is 1"
  84.   System.Console.WriteLine(a + " is " + (int) a); 
  85. // Prints 70
  86. System.Console.WriteLine((int) Status.Pass); 
  87. // Prints Pass
  88. System.Console.WriteLine(Status.Pass);
  89. Operators
  90. VB.NET
  91. 'Comparison
  92. =  <  >  <=  >=  <> 
  93. 'Arithmetic
  94. +  -  *  /
  95. Mod
  96.   (integer division)
  97. ^  (raise to a power) 
  98. 'Assignment
  99. =  +=  -=  *=  /=  =  ^=  <<=  >>=  &= 
  100. 'Bitwise
  101. And  AndAlso  Or  OrElse  Not  <<  >> 
  102. 'Logical
  103. And  AndAlso  Or  OrElse  Not 
  104. 'String Concatenation
  105.  C#
  106. //Comparison
  107. ==  <  >  <=  >=  != 
  108. //Arithmetic
  109. +  -  *  /
  110. %  (mod)
  111. /  (integer division if both operands are ints)
  112. Math.Pow(x, y) 
  113. //Assignment
  114. =  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  -- 
  115. //Bitwise
  116. &  |  ^   ~  <<  >> 
  117. //Logical
  118. &&  ||   ! 
  119. //String Concatenation
  120. +
  121. Choices
  122. VB.NET
  123. greeting = IIf(age < 20, "What's up?""Hello"
  124. 'One line doesn't require "End If", no "Else"
  125. If language = "VB.NET" Then langType = "verbose" 
  126. 'Use: to put two commands on same line
  127. If x <> 100 And y < 5 Then x *= 5 : y *= 2   
  128. 'Preferred
  129. If x <> 100 And y < 5 Then
  130.   x *= 5
  131.   y *= 2
  132. End If 
  133. 'or to break up any long single command use _
  134. If henYouHaveAReally < longLine And _ 
  135. itNeedsToBeBrokenInto2   > Lines  Then _
  136.   UseTheUnderscore(charToBreakItUp) 
  137. If x > 5 Then
  138.   x *= y 
  139. ElseIf x = 5 Then
  140.   x += y 
  141. ElseIf x < 10 Then
  142.   x -= y
  143. Else
  144.   x /= y
  145. End If 
  146. 'Must be a primitive data type
  147. Select Case color   
  148.   Case "black""red"
  149.     r += 1
  150.   Case "blue"
  151.     b += 1
  152.   Case "green"
  153.     g += 1
  154.   Case Else
  155.     other += 1
  156. End Select
  157.  C#
  158. greeting = age < 20 ? "What's up?" : "Hello"
  159. if (x != 100 && y < 5)
  160. {
  161.   // Multiple statements must be enclosed in {}
  162.   x *= 5;
  163.   y *= 2;
  164. if (x > 5) 
  165.   x *= y; 
  166. else if (x == 5) 
  167.   x += y; 
  168. else if (x < 10) 
  169.   x -= y; 
  170. else 
  171.   x /= y;
  172. //Must be integer or string
  173. switch (color)
  174. {
  175.   case "black":
  176.   case "red":    r++;
  177.    break;
  178.   case "blue"
  179.    break;
  180.   case "green": g++;  
  181.    break;
  182.   default:    other++;
  183.    break;
  184. }
  185. Loops
  186. VB.NET
  187. 'Pre-test Loops:
  188. While c < 10
  189.   c += 1
  190. End While Do Until c = 10
  191.   c += 1
  192. Loop 
  193. 'Post-test Loop:
  194. Do While c < 10
  195.   c += 1
  196. Loop 
  197. For c = 2 To 10 Step 2
  198.   System.Console.WriteLine(c)
  199. Next 
  200. 'Array or collection looping
  201. Dim names As String() = {"Steven""SuOk""Sarah"}
  202. For Each s As String In names
  203.   System.Console.WriteLine(s)
  204. Next
  205.  C#
  206. //Pre-test Loops: while (i < 10)
  207.   i++;
  208. for (i = 2; i < = 10; i += 2)
  209.   System.Console.WriteLine(i); 
  210. //Post-test Loop:
  211. do
  212.   i++;
  213. while (i < 10);
  214. // Array or collection looping
  215. string[] names = {"Steven""SuOk""Sarah"};
  216. foreach (string s in names)
  217.   System.Console.WriteLine(s);
  218. Arrays
  219. VB.NET
  220. Dim nums() As Integer = {1, 2, 3}
  221. For i As Integer = 0 To nums.Length - 1 
  222.   Console.WriteLine(nums(i)) 
  223. Next 
  224. '4 is the index of the last element, so it holds 5 elements
  225. Dim names(4) As String
  226. names(0) = "Steven"
  227. 'Throws System.IndexOutOfRangeException
  228. names(5) = "Sarah"
  229. 'Resize the array, keeping the existing
  230. 'values (Preserve is optional)
  231. ReDim Preserve names(6)
  232. Dim twoD(rows-1, cols-1) As Single 
  233. twoD(2, 0) = 4.5
  234. Dim jagged()() As Integer = { _
  235.   New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
  236. jagged(0)(4) = 5
  237.  C#
  238. int[] nums = {1, 2, 3};
  239. for (int i = 0; i < nums.Length; i++)
  240.   Console.WriteLine(nums[i]);
  241. // 5 is the size of the array
  242. string[] names = new string[5];
  243. names[0] = "Steven";
  244. // Throws System.IndexOutOfRangeException
  245. names[5] = "Sarah"
  246. // C# can't dynamically resize an array.
  247. //Just copy into new array.
  248. string[] names2 = new string[7];
  249. // or names.CopyTo(names2, 0);
  250. Array.Copy(names, names2, names.Length); 
  251. float[,] twoD = new float[rows, cols];
  252. twoD[2,0] = 4.5; 
  253. int[][] jagged = new int[3][] {
  254.   new int[5], new int[2], new int[3] };
  255. jagged[0][4] = 5;
  256. Functions
  257. VB.NET
  258. 'Pass by value (indefault), reference
  259. '(in/out), and reference (out)
  260. Sub TestFunc(ByVal x As Integer, ByRef y As Integer,
  261. ByRef z As Integer)
  262.   x += 1
  263.   y += 1
  264.   z = 5
  265. End Sub 
  266. 'c set to zero by default
  267. Dim a = 1, b = 1, c As Integer
  268. TestFunc(a, b, c)
  269. System.Console.WriteLine("{0} {1} {2}", a, b, c) '1 2 5 
  270. 'Accept variable number of arguments
  271. Function Sum(ByVal ParamArray nums As Integer()) As Integer
  272.   Sum = 0
  273.   For Each i As Integer In nums
  274.     Sum += i
  275.   Next
  276. End Function 'Or use a Return statement like C#
  277. Dim total As Integer = Sum(4, 3, 2, 1) 'returns 10 
  278. 'Optional parameters must be listed last
  279. 'and must have a default value
  280. Sub SayHello(ByVal name As String,
  281. Optional ByVal prefix As String = "")
  282.   System.Console.WriteLine("Greetings, " & prefix
  283. " " & name)
  284. End Sub
  285. SayHello("Steven""Dr.")
  286. SayHello("SuOk")
  287.  C#
  288. // Pass by value (in, default), reference
  289. //(in/out), and reference (out)
  290. void TestFunc(int x, ref int y, out int z) {
  291.   x++;
  292.   y++;
  293.   z = 5;
  294. int a = 1, b = 1, c; // c doesn't need initializing
  295. TestFunc(a, ref b, out c);
  296. System.Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5 
  297. // Accept variable number of arguments
  298. int Sum(params int[] nums) {
  299.   int sum = 0;
  300.   foreach (int i in nums)
  301.     sum += i;
  302.   return sum;
  303. int total = Sum(4, 3, 2, 1); // returns 10 
  304. /* C# doesn't support optional arguments/parameters.
  305. Just create two different versions of the same function. */
  306. void SayHello(string name, string prefix) {
  307.   System.Console.WriteLine("Greetings, "  + prefix + " " + name);
  308. }
  309. void SayHello(string name) {
  310.   SayHello(name, "");
  311. }
  312. Exception Handling
  313. VB.NET
  314. 'Deprecated unstructured error handling
  315. On Error GoTo MyErrorHandler
  316. ...
  317. MyErrorHandler: System.Console.WriteLine(Err.Description)
  318. Dim ex As New Exception("Something has really gone wrong.")
  319. Throw ex 
  320. Try
  321.   y = 0
  322.   x = 10 / y
  323. Catch ex As Exception When y = 0 'Argument and When is optional
  324.   System.Console.WriteLine(ex.Message) 
  325. Finally
  326.   DoSomething() 
  327. End Try
  328.  C#
  329. Exception up = new Exception("Something is really wrong."); 
  330. throw up; // ha ha 
  331. try{
  332.   y = 0;
  333.   x = 10 / y;
  334. }
  335. catch (Exception ex) { //Argument is optional, no "When" keyword
  336.   Console.WriteLine(ex.Message);
  337. }
  338. finally{
  339.   // Do something
  340. }
  341. Namespaces
  342. VB.NET
  343. Namespace ASPAlliance.DotNet.Community
  344.   ...
  345. End Namespace 
  346. 'or 
  347. Namespace ASPAlliance 
  348.   Namespace DotNet
  349.     Namespace Community
  350.       ...
  351.     End Namespace
  352.   End Namespace
  353. End Namespace 
  354. Imports ASPAlliance.DotNet.Community
  355.  C#
  356. namespace ASPAlliance.DotNet.Community {
  357.   ...
  358. // or 
  359. namespace ASPAlliance {
  360.   namespace DotNet {
  361.     namespace Community {
  362.       ...
  363.     }
  364.   }
  365. using ASPAlliance.DotNet.Community;
  366. Classes / Interfaces
  367. VB.NET
  368. 'Accessibility keywords
  369. Public
  370. Private
  371. Friend
  372. Protected
  373. Protected Friend
  374. Shared 
  375. 'Inheritance
  376. Class Articles
  377.   Inherits Authors
  378.   ...
  379. End Class 
  380. 'Interface definition
  381. Interface IArticle 
  382.   ...
  383. End Interface 
  384. 'Extending an interface
  385. Interface IArticle
  386.   Inherits IAuthor
  387.   ...
  388. End Interface 
  389. 'Interface implementation</span>
  390. Class PublicationDate
  391.   Implements</strong> IArticle, IRating
  392.    ...
  393. End Class
  394.  C#
  395. //Accessibility keywords
  396. public
  397. private
  398. internal
  399. protected
  400. protected internal
  401. static 
  402. //Inheritance
  403. class Articles: Authors {
  404.   ...
  405. //Interface definition
  406. interface IArticle {
  407.   ...
  408. //Extending an interface
  409. interface IArticle: IAuthor {
  410.   ...
  411. //Interface implementation
  412. class PublicationDate: IArticle, IRating {
  413.    ...
  414. }
  415. Constructors / Destructors
  416. VB.NET
  417. Class TopAuthor
  418.   Private _topAuthor As Integer
  419.   Public Sub New()
  420.     _topAuthor = 0
  421.   End Sub
  422.   Public Sub New(ByVal topAuthor As Integer)
  423.     Me._topAuthor = topAuthor
  424.   End Sub
  425.   Protected Overrides Sub Finalize()
  426.    'Desctructor code to free unmanaged resources
  427.     MyBase.Finalize() 
  428.   End Sub
  429. End Class
  430.  C#
  431. class TopAuthor {
  432.   private int _topAuthor;
  433.   public TopAuthor() {
  434.      _topAuthor = 0;
  435.   }
  436.   public TopAuthor(int topAuthor) {
  437.     this._topAuthor= topAuthor
  438.   }
  439.   ~TopAuthor() {
  440.     // Destructor code to free unmanaged resources.
  441.     // Implicitly creates a Finalize method
  442.   }
  443. }
  444. Objects
  445. VB.NET
  446. Dim author As TopAuthor = New TopAuthor
  447. With author
  448.   .Name = "Steven"
  449.   .AuthorRanking = 3
  450. End With
  451. author.Rank("Scott")
  452. author.Demote() 'Calling Shared method
  453. 'or
  454. TopAuthor.Rank() 
  455. Dim author2 As TopAuthor = author 'Both refer to same object
  456. author2.Name = "Joe"
  457. System.Console.WriteLine(author2.Name) 'Prints Joe 
  458. author = Nothing 'Free the object 
  459. If author Is Nothing Then _
  460.   author = New TopAuthor 
  461. Dim obj As Object = New TopAuthor
  462. If TypeOf obj Is TopAuthor Then _
  463.   System.Console.WriteLine("Is a TopAuthor object.")
  464.  C#
  465. TopAuthor author = new TopAuthor();
  466. //No "With" construct
  467. author.Name = "Steven";
  468. author.AuthorRanking = 3; 
  469. author.Rank("Scott");
  470. TopAuthor.Demote() //Calling static method 
  471. TopAuthor author2 = author //Both refer to same object
  472. author2.Name = "Joe";
  473. System.Console.WriteLine(author2.Name) //Prints Joe 
  474. author = null //Free the object 
  475. if (author == null)
  476.   author = new TopAuthor(); 
  477. Object obj = new TopAuthor(); 
  478. if (obj is TopAuthor)
  479.   SystConsole.WriteLine("Is a TopAuthor object.");
  480. Structs
  481. VB.NET
  482. Structure AuthorRecord
  483.   Public name As String
  484.   Public rank As Single
  485.   Public Sub New(ByVal name As String, ByVal rank As Single) 
  486.     Me.name = name
  487.     Me.rank = rank
  488.   End Sub
  489. End Structure 
  490. Dim author As AuthorRecord = New AuthorRecord("Steven", 8.8)
  491. Dim author2 As AuthorRecord = author
  492. author2.name = "Scott"
  493. System.Console.WriteLine(author.name) 'Prints Steven
  494. System.Console.WriteLine(author2.name) 'Prints Scott
  495.  C#
  496. struct AuthorRecord {
  497.   public string name;
  498.   public float rank;
  499.   public AuthorRecord(string name, float rank) {
  500.     this.name = name;
  501.     this.rank = rank;
  502.   }
  503. }
  504. AuthorRecord author = new AuthorRecord("Steven", 8.8);
  505. AuthorRecord author2 = author
  506. author.name = "Scott";
  507. SystemConsole.WriteLine(author.name); //Prints Steven
  508. System.Console.WriteLine(author2.name); //Prints Scott
  509. Properties
  510. VB.NET
  511. Private _size As Integer
  512. Public Property Size() As Integer
  513.   Get
  514.     Return _size
  515.   End Get
  516.   Set (ByVal Value As Integer)
  517.     If Value < 0 Then
  518.       _size = 0
  519.     Else
  520.       _size = Value
  521.     End If
  522.   End Set
  523. End Property 
  524. foo.Size += 1
  525.  C#
  526. private int _size;
  527. public int Size {
  528.   get {
  529.     return _size;
  530.   }
  531.   set {
  532.     if (value < 0)
  533.       _size = 0;
  534.     else
  535.       _size = value;
  536.   }
  537. foo.Size++;
  538. Delegates / Events
  539. VB.NET
  540. Delegate Sub MsgArrivedEventHandler(ByVal message
  541. As String) 
  542. Event MsgArrivedEvent As MsgArrivedEventHandler 
  543. 'or to define an event which declares a
  544. 'delegate implicitly
  545. Event MsgArrivedEvent(ByVal message As String) 
  546. AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
  547. 'Won'throw an exception if obj is Nothing
  548. RaiseEvent MsgArrivedEvent("Test message")
  549. RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
  550. Imports System.Windows.Forms 
  551. 'WithEvents can't be used on local variable
  552. Dim WithEvents MyButton As Button
  553. MyButton = New Button 
  554. Private Sub MyButton_Click(ByVal sender As System.Object, _
  555.   ByVal e As System.EventArgs) Handles MyButton.Click
  556.   MessageBox.Show(Me, "Button was clicked""Info", _
  557.     MessageBoxButtons.OK, MessageBoxIcon.Information)
  558. End Sub
  559.  C#
  560. delegate void MsgArrivedEventHandler(string message); 
  561. event MsgArrivedEventHandler MsgArrivedEvent; 
  562. //Delegates must be used with events in C#
  563. MsgArrivedEvent += new MsgArrivedEventHandler
  564.   (My_MsgArrivedEventCallback);
  565. //Throws exception if obj is null
  566. MsgArrivedEvent("Test message");
  567. MsgArrivedEvent -= new MsgArrivedEventHandler
  568.   (My_MsgArrivedEventCallback); 
  569. using System.Windows.Forms; 
  570. Button MyButton = new Button();
  571. MyButton.Click += new System.EventHandler(MyButton_Click); 
  572. private void MyButton_Click(object sender,    System.EventArgs e) {
  573.   MessageBox.Show(this"Button was clicked""Info",
  574.     MessageBoxButtons.OK, MessageBoxIcon.Information);
  575. }
  576. Console I/O
  577. VB.NET
  578. 'Special character constants
  579. vbCrLf, vbCr, vbLf, vbNewLine
  580. vbNullString
  581. vbTab
  582. vbBack
  583. vbFormFeed
  584. vbVerticalTab
  585. ""
  586. Chr(65) 'Returns 'A' 
  587. System.Console.Write("What's your name? ")
  588. Dim name As String = System.Console.ReadLine()
  589. System.Console.Write("How old are you? ")
  590. Dim age As Integer = Val(System.Console.ReadLine())
  591. System.Console.WriteLine("{0} is {1} years old.", name, age)
  592. 'or
  593. System.Console.WriteLine(name & " is " & age & " years old.")
  594. Dim c As Integer
  595. c = System.Console.Read() 'Read single char
  596. System.Console.WriteLine(c) 'Prints 65 if user enters "A"
  597.  C#
  598. //Escape sequences
  599. n, r
  600. t
  601. Convert.ToChar(65) //Returns 'A' - equivalent to Chr(num) in VB
  602. // or
  603. (char) 65 
  604. System.Console.Write("What's your name? ");
  605. string name = SYstem.Console.ReadLine();
  606. System.Console.Write("How old are you? ");
  607. int age = Convert.ToInt32(System.Console.ReadLine());
  608. System.Console.WriteLine("{0} is {1} years old.",  name, age);
  609. //or
  610. System.Console.WriteLine(name + " is " +  age + " years old."); 
  611. int c = System.Console.Read(); //Read single char
  612. System.Console.WriteLine(c); //Prints 65 if user enters "A"
  613. File I/O
  614. VB.NET
  615. Imports System.IO 
  616. 'Write out to text file
  617. Dim writer As StreamWriter = File.CreateText
  618.   ("c:myfile.txt")
  619. writer.WriteLine("Out to file.")
  620. writer.Close() 
  621. 'Read all lines from text file
  622. Dim reader As StreamReader = File.OpenText
  623.   ("c:myfile.txt")
  624. Dim line As String = reader.ReadLine()
  625. While Not line Is Nothing
  626.   Console.WriteLine(line)
  627.   line = reader.ReadLine()
  628. End While
  629. reader.Close() 
  630. 'Write out to binary file
  631. Dim str As String = "Text data"
  632. Dim num As Integer = 123
  633. Dim binWriter As New BinaryWriter(File.OpenWrite
  634.   ("c:myfile.dat"))
  635. binWriter.Write(str)
  636. binWriter.Write(num)
  637. binWriter.Close() 
  638. 'Read from binary file
  639. Dim binReader As New BinaryReader(File.OpenRead
  640.   ("c:myfile.dat"))
  641. str = binReader.ReadString()
  642. num = binReader.ReadInt32()
  643. binReader.Close()
  644.  C#
  645. using System.IO; 
  646. //Write out to text file
  647. StreamWriter writer = File.CreateText
  648.   ("c:myfile.txt");
  649. writer.WriteLine("Out to file.");
  650. writer.Close(); 
  651. //Read all lines from text file
  652. StreamReader reader = File.OpenText
  653.   ("c:myfile.txt");
  654. string line = reader.ReadLine();
  655. while (line != null) {
  656.   Console.WriteLine(line);
  657.   line = reader.ReadLine();
  658. }
  659. reader.Close(); 
  660. //Write out to binary file
  661. string str = "Text data";
  662. int num = 123;
  663. BinaryWriter binWriter = new BinaryWriter(File.OpenWrite
  664.   ("c:myfile.dat"));
  665. binWriter.Write(str);
  666. binWriter.Write(num);
  667. binWriter.Close(); 
  668. //Read from binary file
  669. BinaryReader binReader = new BinaryReader(File.OpenRead
  670.   ("c:myfile.dat"));
  671. str = binReader.ReadString();
  672. num = binReader.ReadInt32();
  673. binReader.Close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章