Example 033 Scope of variables and processes

Scope in Visual Basic

The scope of a declared element is the collection of all code that can reference it, and there is no need to qualify its name or provide it through the Imports statement (.net namespace and type) . Elements can have scope at one of the following levels:

 
level Explanation
Block range Only available within the code block that declares it
Process scope Available to all code in the process of declaring it
Module scope Applies to all code in the module, class or structure that declares it
Namespace scope Can be used to declare all code in its namespace

This level from the minimum scope (block) to the widest (namespace) range schedule, the most narrow range means that an element can be referenced without defining the minimum code set. For more information, see "Scope Level" on this page.

Specify scope and define variables

Specify the scope when declaring an element. The scope may depend on the following factors:

  • The area where the element is declared (block, procedure, module, class or structure)

  • Namespace containing element declarations

  • The access level declared for the element

Be careful when defining variables with the same name but different scopes, as doing so may lead to unexpected results. For more information, see  References to Declared Elements .

Scope level

The programming element can be used in the entire area where it is declared. All codes in the same area can refer to elements without qualifying their names.

Block range

A block is a set of statements contained in start and stop statement statements, as follows:

  • Do with Loop

  • For [ Each] And Next

  • If with End If

  • Select with End Select

  • SyncLock with End SyncLock

  • Try with End Try

  • While with End While

  • With with End With

If you declare a variable in a block, you can only use it within that block.

 

A small example:

Module Module1
    Dim i As Integer = 1000
    Public Class okay
        Public i As Integer = 5
        Public Sub geti()
            Console.WriteLine("Okay类的i的值:" & i)
        End Sub
    End Class

    Public Sub seti()
        Dim i As Integer
        i = 100
        Console.WriteLine("seti模块的Public中的i:" & i)
    End Sub
    Sub Main()
        Dim ok As New okay
        ok.geti()

        Console.WriteLine ("i value in Module1:" & i)

        set ()

        Console.Read()
    End Sub

End Module
 

Published 146 original articles · praised 0 · visits 2745

Guess you like

Origin blog.csdn.net/ngbshzhn/article/details/105563370