[转] C # and VB.NET syntax comparison

xiaoxiao2021-03-19  194

[转] C # and VB.NET syntax comparison

The syntax of C # and VB.NET is still relatively large. Maybe you will C #, maybe you will vb.

Putting them together to compare you, you will read it quickly, and master another language.

I believe that the table below will help you.

Comments vb.net 'Single Line ONLY

REM SINGLE LINE ONLY C # // Single Line

/ * Multiple

Line * /

/// xml Comments on single line

/ ** XML Comments on Multiple Lines * / Data Types VB.NET 'Value Types

Boolean

Byte

Char (Example: "a")

Short, integer, long

SINGLE, DOUBLE

Decimal

Date

'Reference Types

Object

String

DIM X as integer

System.console.writeLine (x.gettype ())

System.console.writeline (TypeName (X))

'Type Conversion

DIM D As Single = 3.5

DIM I as integer = ctype (d, integer)

i = CINT (D)

i = int (d) c # // value type

Bool

Byte, sbyte

Char (Example: 'A')

Short, Ushort, Int, Uint, Long, Ulong

Float, Double

Decimal

Datetime

// REFERENCE TYPES

Object

String

INT X;

Console.writeline (x.gettype ())

Console.writeLine (Typeof (int))

// Type Conversion

FLOAT D = 3.5;

INT i = (int) D constants VB.NET const Max_authors as integer = 25

Readonly min_rank as single = 5.00 c # const amount in_authors = 25;

Readonly float min_ranking = 5.00; ENUMERATIONS VB.NET ENUM ACTION

Start

'Stop Is A Reserved Word

[STOP]

Rewind

Forward

END ENUM

ENUM STATUS

FLUNK = 50

Pass = 70

Excel = 90

END ENUM

Dim a as an action = action.stop

IF a <> action.start the_

'Prints "STOP IS 1"

System.Console.writeline (a.tostring & "is" & a)

'Prints 70

System.console.writeline (status.pass)

'Prints Pass

System.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));

// Prints 70

System.console.writeline (int) status.pass;

// Prints Pass

System.console.writeline (status.pass); Operators VB.NET 'Comparison

= <> <=> = <>

'AritHmetic

- * /

MOD

(Integer Division)

^ (Raise to a power)

'Assignment

= = - = * = / = = ^ = << = >> = & =

'Bitwise

And and Andalso or orelse not << >>

'Logical

And and Andalso or orelse not

'String ConcateNation

& C # // Comparist

== <> <=> =! =

// 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 "Endiff", NO "ELSE"

If Language = "VB.NET" TENGTYPE = "Verbose"

'Use: to put two commands on Same Line

IF x <> 100 and y <5 THEN X * = 5: y * = 2

'Preferred

IF x <> 100 and y <5 THEN

X * = 5

Y * = 2

END IF

'or to Break Up any long salesle command use _

IF HenyouhaveareAlly

ItneedStobeBrokeninto2> Lines Then _usetheunderscore (ChartobreakiTup)

IF x> 5 THEN

X * = Y

Elseif x = 5 THEN

X = Y

Elseif x <10 THEN

X - = y

Else

X / = Y

END IF

'Must Be a Primitive Data Type

SELECT CASE Color

Case "Black", "Red"

R = 1

Case "blue"

B = 1

Case "Green"

G = 1

Case Else

Other = 1

End 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 string

Switch (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 = 1

End while do until c = 10

C = 1

Loop

'POST-TEST LOOP:

Do While C <10

C = 1

Loop

For c = 2 to 10 step 2

System.console.writeLine (C)

NEXT

'Array or Collection looping

DIM 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 looping

String [] name = {"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 elements

DIM Names (4) AS String

Names (0) = "steven"

'Throws system.indexoutofrangeexception

Names (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.5

DIM 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

Console.writeline (NUMS [I]);

// 5 is The size of the array

String [] Names = new string [5];

Names [0] = "steven";

// throws system.indexoutofrangeexception

Names [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 rt [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 in

BYREF Z AS INTEGER)

X = 1

Y = 1

z = 5

End Sub

'c set to zero by Default

DIM A = 1, B = 1, C as integer

Testfunc (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

NEXT

End 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 Value

Sub Sayhello (Byval Name As String,

OPTIONAL BYVAL Prefix As String = "")

System.Console.writeline ("Greetings," & Prefix

& "& name)

End Sub

Sayhello ("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 Initializing

TestFunc (A, REF B, OUT C);

System.console.writeline ("{0} {1} {2}", A, B, C); // 1 2 5

// accept variable number of arguments

Int 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 HANDLING

ON 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

DOSMETHING ()

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.dot.com.community

...

End Namespace

'OR

Namespace aspalliance

Namespace DotNet

Namespace Community

...

End Namespace

End Namespace

End Namespace

Imports aspalliance.dotnet.community C # namespace aspalliance.dot.com.community {

...

}

// OR

Namespace aspalliance {

Namespace dotnet {

Namespace Community {

...

}

}

}

Using aspalliance.dotnet.community; classes / interfaces vb.net 'Accessibility Keywords

Public

Private

Friend

Protected

Protected Friend

Shared

'Inheritancence

Class Articles

Inherits Authors

...

END CLASS

'Interface Definition

Interface IATICLE

...

End interface

'Extending an interface

Interface IATICLE

Inherits IAUTHOR

...

End interface

'Interface Implementation

Class PublicationDate

Implements iArticle, IRating

...

End Class C # // Accessibility Keywords

public

Private

Internal

protected

protected in

Static

// inheritance

Class Articles: Authors {

...

}

// Interface definition

Interface iArticle {

...

}

// extending an interface

Interface iArticle: IAUTHOR {

...

}

// Interface Implementation

Class publicationDate: iArticle, Irating {

...

CONSTRUCTORS / DESTRUCTORS VB.NET CLASS TOPAUTHOR

Private _topauthor as integerpublic sub new ()

_TopAuthor = 0

End Sub

Public Sub New (Byval TopAuthor As Integer)

Me._topauthor = TopAuthor

End Sub

Protected overrides sub firmize ()

'Desctructor code to free unmanaged resources

Mybase.finalize ()

End Sub

End class c # Class TopAuthor {

Private int _topauhouse;

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 TopAuthor

With Author

.Name = "steven"

.Authorranking = 3

End with

Author.rank ("Scott")

Author.demote () 'Calling Shared Method

'OR

TopAuthor.rank ()

DIM Author2 as TopAuthor = Author 'Both Refer to Same Object

Author2.name = "joe"

System.console.writeline (Author2.name) 'Prints Joe

Author = Nothing 'Free the Object

IF author is nothing the _

Author = New TopAuthor

DIM OBJ As Object = New TopAuthor

If TypeOf Obj Is TopAuthor Then_

System.Console.writeline ("is a topauthor object.") C # TopAuthor Author = New TopAuthor ();

// no "with" construct

Author.name = "steven";

Author.Authorrancing = 3;

Author.rank ("scott");

TopAuthor.Demote () // Calling staticMethod

TopAuthor Author2 = Author // Both Refer to Same Object

Author2.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 AuthorRecordpublic 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 Sub

End structure

DIM Author as authorrecord = New AuthorRecord ("Steven", 8.8)

Dim Author2 as AuthorRecord = Author

Author2.name = "scott"

System.console.writeline (Author.Name) 'Prints Steven

System.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 = Author

Author.name = "scott";

SystemConsole.writeline (Author.Name); // Prints Steven

System.console.writeline (Author2.name); // Prints Scott Properties VB.NET Private_size As INTEGER

Public 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 set

End Property

Foo.size = 1 C # private int _size;

Public int size {

Get {

Return_size;

}

SET {

Value <0)

_size = 0;

Else

_size = value;

}

}

Foo.size ; delegates / events vb.net delegate Sub MsgarriveDeventrandler (Byval Message

As string

Event MsgarriveDevent As MsgarriveDeventhandler

'or To Define An Event Which Declares A

'Delegate IMPLICITLY

Event MsgarriveDevent (Byval Message As String)

AddHandler MsgarriveDevent, Addressof my_msgarrivedcallback

'WON' THROW An Exception IF Obj Is Nothingraiseevent MsgarriveDevent ("Test Message")

REMOVEHANDAL MSGARRIVEDEVENT, Addressof my_msgarrivedcallback

Imports System.Windows.Forms

'WitHevents Can't Be Used On Local Variable

Dim withevents mybutton as button

MyButton = 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", _

MessageboxButton.ok, MessageBoxicon.information)

End Sub C # delegate Void MsgarriveDeventHandler (String Message);

Event MsgarriveDeventHandler MsgarriveDevent;

// delegates Must Be Used with events in c #

MsgarriveDevent = new msgarrivedeDeventhandler

(My_MsgarriveDeventCallback);

// throws Exception if Obj Is Null

MsgarriveDevent ("Test Message");

MsgarriveDevent - = new msgarrivedeDeventhandler

(My_MsgarriveDeventCallback);

Using system.windows.forms;

Button myButton = new button ();

MyButton.Click = new system.eventhandler (myButton_Click);

Private void mybutton_click (Object Sender,

System.Eventargs e) {

Messagebox.show (this, "Button Was Clicked", "Info",

MessageboxButtons.ok, MessageBoxicon.information;

} Console I / O VB.NET 'Special Character Constants

VBCRLF, VBCR, VBLF, VBNEWLINE

vbnullstring

VBTAB

VBBACK

VBFormfeed

VBverticalTab

""

CHR (65) 'RETURNS' A '

System.Console.write ("What's your name?")

Dim name as string = system.console.readline ()

System.Console.write ("How old is you?")

DIM AGE AS INTEGER = VAL (System.Console.Readline ())

System.console.writeline ("{0} is {1} Years old.", Name, age) 'OR

System.console.writeline (Name & "IS" & Age & "Years Old.")

DIM C AS Integer

C = system.console.read () 'Read Single Char

System.console.writeline (c) 'Prints 65 if User Enters "a" c # // escape sequencees

n, r

t

Convert.TOCHAR (65)

// Returns 'A' - Equivalent to Chr (NUM) in VB

// OR

(char) 65

System.Console.write ("What's your name?");

String name = system.console.readline ();

System.Console.write ("How old is you?");

Int Age = Convert.Toint32 (System.Console.Readline ());

System.console.writeLine ("{0} is {1} years old.",

Name, AGE;

// OR

System.console.writeLine (Name "IS"

Age "Years Old.");

INT c = system.console.read (); // read single char

System.console.writeLine (C);

// Prints 65 if User Enters "a" File I / O VB.NET Imports System.io

'Write Out to Text File

DIM Writer as streamwriter = file.createtext

("c: myfile.txt")

Writer.writeline ("Out to File.")

Writer.close ()

'Read All Lines from Text File

Dim 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 while

Reader.close ()

'Write Out to Binary File

DIM STR AS STRING = "Text Data"

DIM NUM AS INTEGER = 123

Dim binwriter as new binarywriter (file.openwrite

("c: myfile.dat"))))

BinWriter.write (STR)

Binwriter.write (NUM)

BinWriter.Close ()

'Read from Binary File

Dim 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 File

Streamwriter Writer = file.createtext

("c: myfile.txt");

Writer.writeline ("Out to File.");

Writer.close ();

// read all Lines from Text File

StreamReader 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 File

String 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 file

BinaryReader Binreader = New BinaryReader (file.openread

("c: myfile.dat"))));

Str = binreader.readstring ();

Num = binreader.readint32 ();

BinReader.close ();

Note: This article is transferred from http://www.lemongtree.com/280.html.aspx

转载请注明原文地址:https://www.9cbs.com/read-130277.html

New Post(0)