How to turn from VB to VB.NET - VB6 programmers to .NET

xiaoxiao2021-03-06  108

(Posted in "9CBS Development Master" March 2003)

Author mahesh chand

Translation Han Lei

Visual Basic .NET is one of the main components in the Microsoft Visual Studio .NET kit. The .NET version of Visual Basic adds more characteristics, and evolved into programming languages ​​that fully faced objects (like C ). This article will introduce the new features of VB.NET and compare the difference between VB6.0 / VB.NET, explaining how to write simple applications with VB.NET.

1.1 What is VB.NET? VB.NET is a subsequent version of VB6.0. Microsoft launches new programming and operating system framework ---.net, supports multiple languages ​​to develop applications using public .NET libraries, which are running on the .NET Framework. Use Visual Basic to program on .NET Framework, this is VB.NET.

First, let me show the simplest console program in VB.NET: Hello World.

1.2 Hello, World! "Hello World!" Is a representative program for beginners to learn Windows programming. Our first program is called "Hello VB.NET World!". The program outputs a sentence in the console: "Hello VB.NET World!", The code is as follows:

Code 1.1: Hello VB.NET World Example Imports SYSTEM

Module Module1

Sub

Main

()

System.Console.writeline ("Hello VB.NET World!")

End Sub

End module

1.3 VB.NET Editor and Compiler You can write the above code in any text editor such as Notepad or VS.NET IDE, and then save as HelloWorld.vb. After the code is written, or in the command line, either compile it in VS.NET IDE. In Microsoft .NET Framework SDK already included VB.NET compiler vbc.exe [1], can be called from IDE or command lines. To build HelloWorld.vb from the command line, enter the command line window

VBC HelloWorld.vb /out:heloworld.exe / T: EXE

After the completion, HelloWorld.exe is created in the current directory. Double-click the icon or execute in the command line, the program is running correctly in the resource management. Congratulations on the ranks of VB.NET developers.

IMPORTS statement

As you know, most of the .NET type is defined in the name space (Namespace). Namespace is a scope of definition and management categories. Look at .NET Framework Class Library, you can see hundreds of Namespace. For example, System Namespace includes type definitions such as console, objects. If you want to use the CONSOLE class, you need to import System Namespace with the Imports instruction. As follows:

The Imports System can even use the namespace in the name without using Import import. The following example shows the "Hello World!" Program without import:

Code 1.2: Hello VB.Net World Example Module Module1

Sub

Main

()

System.Console.writeline ("Hello VB.NET World!")

End Subend Module1.4 Analysis "Hello VB.NET World!" The first line of the program is:

Imports System; System Namespace defines the Console class, which is used to read and write the console (command line window). Then you define a module: module module1 ... End Module All VB programs include a main () method, that is, the application entry point. In an example program, we call console.writeline () to write "Hello VB.NET World!" To the console:

Sub

Main

()

Console.Writeline ("Hello VB.NET World!") The End Subwriteline () method belongs to the Console class, which is responsible for writing a string with row ends to the console. As mentioned earlier, the Console class is defined in System NameSpace, and you control the class members by direct reference.

The Console class is responsible for reading and writing system console. Read the console input with the READ and READLINE method, output the WriteLine method to the console.

Table 1.1 CONSOLE class definition method

method

use

example

Reta

Read in a single character

INT i = console.read ();

Readline

Read in one way

String str = console.readline ();

Write

Write a line

Console.write ("WRITE: 1");

WriteLine

Write a row and bring up the end of the end

Console.writeline ("Test Output Data with Line");

1.5 VB.NET What new character? As subsequent versions of VB6.0, VB.NET is more stable and fully faced. Maybe you still remember that VB6.0 supports inheritance, overloading, and interface, so it is not true to object. VB.NET supports these object-oriented properties. VB6.0 has two weak links - multi-threaded and abnormal processing. In VB.NET, develop multi-threaded applications and use C / C # should not be borne, structured exception handling is also supported. We will explain these features in detail later.

Below is a list of characteristics of VB.NET -

· Object-oriented programming language. Support inheritance, overload, interface, shared members, and constructors. · Supports all CLS features, such as access control .NET class, interact with other .NET language, metadata, public data type, commission, and more. · Multithreaded support. · Structural exception handling. 1.6 The namespace discussed our first VB.NET program in front of the collection. The program is first attracting that the namespace is named space (Namespace). In the .NET Reference document, you will find that each class belongs to a Namespace. So what is NameSpace?

A NameSpace is a logical combination of classes and components that are destined to define .NET Class by category. Microsoft borrows C Class Packaging concept: Namespace to describe this combination. Components in .NET Framework are called assembly. All .NET code is defined in hundreds of library files (DLLs). Namespace organizes classes defined in Assembly. A NameSpace can include multiple Assembly, one assembly can also be defined in multiple Namespace. The root node of the Namespace tree is System Namespace. In .NET Library, each class is defined in a similar category. For example, System.Data NameSpace consists of only data related classes. Similarly, System.Multithreading only includes multi-threaded classes.

When you create a new application when you use .NET, C #, VB.NET, C . Net, etc., you will notice that each application is defined as a Namespace, and all Class is attributed to this namespace. . These CLASS can be accessed by reference to this Namespace. In .NET, the code is compiled into an intermediate language (IL), and IL code, metadata, and other resource files are stored in Assembly. The same Assembly can be attached to one or more EXE / DLLs. All .Net libraries are stored in Assembly. 1.7 VB.NET: The programming language of the object is abstract, packaged, polymorphism, and inheritance is four basic properties for object-oriented languages. VB6.0 does not support inheritance, while VB.NET is not. So, like C , VB.NET is also a programming language that completely faces objects.

Class and modulevb.net create a Class with a Class ... End Class statement. Each VB.NET includes at least a MODULE (module). Module is implemented in Module ... End Module statement. The main module of the application is the main method, that is, the application entry point.

Like VB6.0, the method can be defined using the function / sub keyword. The following example shows how to create a Class, add a method, and call the method from the main program: imports system

Module Module1

Sub

Main

()

DIM CLS as TestClass = New TestClass

Console.WriteLine (Cls.Mymethod)

End Sub

Class testclass

Function mymethod () AS STRING

Return "Test Method"

END FUNCTION

END CLASS

The End ModuleProperty property is a common description of class variables. Property ... End Property statement is used to create Property. The GET / SET method for the property is used to obtain and set attribute values, respectively. In the following example, DATA is the properties of TestClass.

Imports system

Imports system.console

Module Module1

Sub

Main

()

DIM CLS as TestClass = New TestClass

WriteLine (Cls.Mymethod)

WriteLine (cls.data)

CLS.DATA = "New Data"

WriteLine (cls.data)

End Sub

End module

Class testclass

Private stradata as string = "some data"

Function mymethod () AS STRING

Return "Test Method!"

END FUNCTION

'Adding Data Property to the Class

Public property data () AS STRING

Get

Return strdata

END GET

Set (byval value as string)

strdata = value

End set

End Property

The overloaded VB.NET is overloaded by overload keyword support. With this keyword, you can define the same name but different parameters.

The class member access domain has introduced several new keywords in addition to the original private and public, VB.NET. All access domain keyword lists are as follows: Keywords

Scope

Private

Limited to Class inside

Public

Can be accessed from CLASS

Friend

Ded to the application to the Class belong

Protected

Can only be accessed by Class and its derived class

Protected Friend

Can be accessed by Class, Application, and Deportation

Inheritance is the most commonly used technique for object-oriented programming languages. Inheritance allows you to reuse class code and features.

VB.NET supports inheritance, and VB6.0 does not support. The benefit of inheritance is that you can use any people to write a class, from these classes, and then call the parent class function in their own class. In the example below, Class B derived from Class A, we will call Class A from Class B Methoda.

Imports system

Imports system.console

Module Module1

Sub

Main

()

DIM BOBJ AS B = New B

WriteLine (bobj.methoda ())

End Sub

End module

'Class a Defined

Public Class A

Function methoda () AS STRING

Return "Method a is caled."

END FUNCTION

END CLASS

'Class B, Inherited from Class A. All Members (Public and Protected)

'Can Be Access Via B NOW.

Public Class B

Inherits a

Function methodb () AS STRING

Return "Method B Is Called."

END FUNCTION

END CLASS

Multiple custom Class can be derived from a Class, or a custom Class is derived from multiple CLASs.

Sharing members of shared members are shared by all entities of the class. Shared members may be attributes, methods, or fields / value domains. When you don't want users to fully control their class, shared members are quite useful. For example, you can develop a class library that allows users to use part of them through shared members.

Shared members can be referenced by Class itself without having to pass the entity of the class. For example: Module Module1

Sub

Main

()

WriteLine (A.Methoda ())

End Sub

End module

'Class a Defined

Public Class A

Shared function methoda () AS STRING

Return "Method a is caled."

END FUNCTION

END CLASS

A big weakness of multi-thread VB languages ​​is the lack of ability to write free threaded programs. In .NET Framework, all languages ​​share CRL (Common Runtime Library, public run), that is, you can write the same program with VB.NET, C # or other .NET language.

System.Threading Namespace defines a thread class. We only need to introduce System.Threading Namespace to use the thread class.

System.Threading.Thread class provides thread objects to create or destroy threads using the Thread class.

Creating a thread Create a new thread using the Thread class, then start using the thread.start method. The thread constructor accepts a parameter that indicates the procedure you want to execute in the thread. In the following example, I want to execute a SecondThread process in the second thread of the osread1 (one entity of the Thread class): OtHread1 = New Thread (Addressof SecondThread)

Secondthread Procedure Looks Like Below:

Public Sub Secondthread ()

DIM I as integer

FOR i = 1 to 10

Console.writeLine (I.ToString ())

NEXT

End Sub

Then, call thread.start () to start thread:

Othread1.start ()

The following code creates two second threads:

Imports system

Imports system.threading

Module Module1

Public Othread1 As Thread

Public Othread2 as Thread

Sub

Main

()

Othread1 = New Thread (Addressof SecondThread)

Othread2 = New Thread (Addressof thirdthread)

Othread1.start ()

Othread2.start ()

End Sub

Public Sub Secondthread ()

DIM I as integer

FOR i = 1 to 10

Console.writeLine (I.ToString ())

NEXT

End Sub

Public Sub Thirdthread ()

DIM I as integer

FOR i = 1 to 10

Console.WriteLine ("a" i.tostring ())

NEXT

End Sub

End module

Destructive thread calls the Abort method to destroy (abort) a thread. Before calling Abort, make sure to use Isalive to determine the thread at the active state.

IF osread1.isalive dam

Othread1.abort ()

END IF

Pause threads can use the SLEEP method to suspend the thread execution. The SLEEP method accepts a parameter in milliseconds, indicating how long the thread should be suspended.

The following example allows threads to pause 1 second:

Othread2.sleep (1000) You can also use Suspend and Resume methods to hang and continue thread execution.

Setting the thread priority Thread class Priority property is used to set thread priority. This property can be set to Normal, ABOVENORMAL, BELOWNORMAL, HIGHEST, and LOWEST. Such as:

OtHread2.Priority = ThreadPriority.Highest Thread with Apartment Using ApartmentState Properties Set the Apartment type of thread, this property value can be STA, MTA or Unknown [2]:

OtHread.ApartmentState = ApartmentState.mtamts means using multi-threaded mode, and STA can only be single-threaded.

Public Enum ApartmentState

{

STA = 0,

MTA = 1,

Unknown = 2,

}

1.8 Structured abnormal processing exception handling is also called an error handling. As a VB programmer, you must have the phrase of the VB6.0 error handling statements in ON ERROR GOTO and ON ERROR RESUME NEXT. This type of error handling is called unstructure exception handling. In VB.NET, Microsoft has introduced a structural exception handling mechanism. VB.NET supports typecatch..finally controls similar to C . The Try..catch..finally structure is as follows: try 'may result in an abnormal code

Catch

'Treatment of exception when an exception occurs

Finally

'Clearing the site

END TRY

The TRY statement block is used to throw an exception. If an abnormality occurs, processed in the CATCH statement block. Finally statement block is optional and is especially useful when you need to release resources.

1.9 VB6.0 and VB.NET differ in except for the language evolution described above, there are some grammar changes. All of these languages ​​and grammar changes in MSDN, this article is only a brief introduction.

Data Type changes VB.NET Some data types are improved. Here is a changing comparison table.

type of data

VB6.0

VB.NET

Integer

16 Bit Size

32 Bit Size

Long

32 Bit Size

64 Bit Size

Currency

Used to store large floating point numbers

Alternative to Decimal, support higher precision

Variant

Arbitrary type data can be stored

Alternative to the Object type, you can also store any type of data, but the result is better

Date

Date type is stored as Double

Introduce the DateTime type for storing the date of different formats

In VB.NET, the Short data type is 16 bits. SHORT, INTEGER and LONG are equivalent to the CLR's System.Int16, System.Int32, and System.Int64 types. Variable declaration changes in VB6.0, variable declarations have many restrictions. One of them is that multiple variables cannot be declared. If you must declare multiple variables in a row, you must specify the type of each variable, otherwise it will be defaulted to a Variant type.

DIM A1, A2 AS INTEGER DIM A3 AS INTEGER, A4 AS INTEGER A1 in the first row is a Variant type, and A2 is an Integer type. Both variables in the second line are Integer types. VB.NET supports multiple variables, for example:

DIM A1, A2, A3 AS INTEGER variable initialization is another problem. Can't declare and initialize variables at the same time in VB6.0, while VB.NET supports this feature.

Dim name as string = "mahesh" system.console.write (name) declared that constitutive constant can also be followed: const dt_count as integer = 23 new keyword. In VB.NET, the New keyword is used to create an object. Since the data type is an object, the New keyword is used to create a data type object.

DIM I as integer = new integer () i = 10System.console.writeline (i.tostring ()) Code block level support. Like C , VB.NET supports a scope of the code block level. The variable declared in the statement block is only valid within the block.

For i = 1 to 10dim p as longsystem.console.writeline (i.tostring ()) NextSystem.console.writeline (p.tostring ()) This code will receive a compilation error in VB.NET because P is in For ..NEXT statement is not accessible. This code can be passed in VB6.0. Improved type safety

In VB6.0, when you declare a reference to an external process, you can specify any type of parameter as ANY. The ANY keyword is forbidden to check, allowing any data type to incorporate and return.

VB.NET does not support an ANY keyword. You must specify the data type of each parameter and the return value. The array VB.NET logs a significant change in array.

Array range. In VB.NET, you need to pay special attention to array range issues. The VB6.0 default array is 0, and the number of elements in the rare is plus one of the array upper bounds. The following array limits are from A (0) to A (10), with a total of 11 elements:

DIM A (10) AS Single can use Option Base to change the lower boundary value of 1. In VB.NET, the arrays and C , the lower bound value is 0, and Option Base is not supported. Note: The MSDN document indicates that the array can only include the number of elements equal to its size, for example: DIM A (10) AS INTEGER can only include 10 elements (from A (0) to A (9)), but in compiling the following paragraph I found it well in the code, and it looked at 11 elements in an array.

DIM A (10) AS INTEGER A (0) = 12 A (2) = 24 A (10) = 23 System.Console.writeline (a (0) .tostring ()) System.Console.writeline (A (10) .Tostring ()) System.console.writeline (iBound (a) .tostring ()) (LBound (a) .tostring ()) LBound and Ubound return 0 and 10 respectively. Redim and fixed array. You can specify an array of fixed lengths in VB6.0.

DIM Arrweekdays (0 to 6) AS Integer

The arrweekdays array here is a fixed length, and the length cannot be changed with the redim statement. VB.NET does not support fixed length arrays, so Redim is always valid.

An array can be declared in two ways: DIM ArrweekDays (6) as integerim arrweekdays () AS integer = {1, 2, 3, 4, 5, 6} Redim statement. In VB6.0, Redim is used to initialize the dynamic array. You cannot use it as a statement in VB.NET. Redim can only be used to change the length of the array, but the array dimensions cannot be changed.

Variant's Variant data type in Objectvb6.0 can store any type variable, and Object in VB.NET has the same capabilities.

Arithmetic operator VB.NET supports shortcuts similar to C . The following table shows the difference between the routine operations and the shortcut operation. Shortcuts can also be used in *, /, |, & and other operators.

Operation conventional syntax shortcut addition a = a 5 a = 5 subtraction a = a - 5 a - 5 fixed length string

In VB6.0, you can specify its length when declaring strings. VB.NET does not support a fixed length string.

The AND, OR or XOR statement in Boolean operator VB6.0 is a bit operator. In VB.NET, they are Boolean operators. Execute these operations will return TRUE or FALSE. VB.NET introduces a new operator to complete a bitwise operation. Operator Description BitNot Bits ANDBITOR Bit OrbitXor Bits XorbitNOT Bit NOT Structure and Custom Type In VB6.0, you create structural or custom types using Type ... End Type. E.g:

Type stdrec

Stdid as integer

STDNAME AS STRING END TYPE

VB.NET introduces a new syntax: structure. Type ... End Type is no longer supported. Structure ... End structure is the same as C usage. You can specify an accessible domain for each element in the structure, such as public, protected, friend, protected, private, and more. E.g:

Structure stdrec

Public stdid as integer public stdname as string

The Structures in Private Stdinternal AS String End Structurevb.NET can also have methods and properties like classes. NEW and NOTHING keywords VB6.0, as new and nothing keys are used to declare an object and initialize it. VB.NET does not support implicitly created objects. As mentioned in the words, even the data type is object. You can create data types or objects with the following two ways: DIM I as Integer Dim I as integer = new integer () // do sometying if i = nothing the end if it does not support SET statement VB6.0 Use the SET statement to assign objects. For example: set myobj = new myObjectSet a = b In VB.NET, it is not necessary to use the SET assignment object. For example: myobj = new myobj () a = b process changes in the grammar in VB.NET has changed many changes. For example, a process called C process call mode, ByVal is the default type, Optional keyword, Return statement, and more. Similar to C process call mode VB6.0 allows no bracket calling process (SUB). However, when you call a function or SUB with a Call statement, be sure to use parentheses. For example: DIM I AS INTEGERCALL EVALUATEDATA 2, i In VB.NET, all method calls require parentheses, while the Call statement is optional. BYVAL is the default parameter type in VB6.0, when the function or SUB is called the default type. That means that all changes will be reflected in the incoming variable. VB.NET changes this way. Now, the default parameter type is BYVAL (pass value). Optional Keyword VB6.0 Using the OPTIONAL keyword can be used to make the user decide to pass a default value, then call the ismissing function to determine whether the parameter is valid. In VB.NET, each optional parameter must declare its default value without calling the ismissing function. For example: SUB MyMethod (optional byvali as integer = 3)

RETURN statement VB.NET's return statement is similar to C . Use the RETURN statement to return control from the process to the caller. In VB6.0, the return statement is used with the GOSUB statement. VB.NET no longer supports a GOSUB statement. The change in process control The following is a modification of VB.NET pairs process control statements: 1. Gosub is no longer supported. 2. Call, function and sub statements can be used to call the process. 3. ON ... GOSUB and ON ... GOTO statements are no longer supported. You can use the SELECT CASE statement to replace. 4. While ... Wend statement is now changed to the While ... End While statement. No longer supporting the Wend key. Small junction Visual Basic .NET is the .NET version of Visual Basic. Through this article you know the basic concepts of VB.NET, it also examines VB.NET from the perspective of VB6.0 developers. [1] Translation: This means you can develop VB.NET without purchasing VS.Net

[2] MTA-Single Threaded Apartment; MTA-Multi Threaded Apartment

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

New Post(0)