The Visual Basic .NET Programming Language

 <  Day Day Up  >  

All fields and methods in a Visual Basic .NET program must be contained within a type. In the examples in previous chapters, the simplest type, a module , was used. Modules are just containers for fields and methods, and unlike types such as classes and structures, they are rarely referred to directly.

NOTE

Modules in Visual Basic .NET should not be confused with the .NET Framework's concept of "modules," which are compiled files that can be used to build assemblies made up of multiple files.

Normally, members of a container can only be used by qualifying them with the name of the container. However, because the name of a module is usually not important, the members of a module can be used without qualifying them with the module's name.

Module Test Sub Main() Console.WriteLine(Add(10, 20)) End Sub End Module Module Math Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Return x + y End Function End Module

In this example, the Math module contains a function named Add , which the module Test can call without referring to Math at all. The module name can be omitted even if the name is being qualified with other names .

Module Test Sub Main() Console.WriteLine(Acme.Add(10, 20)) End Sub End Module Namespace Acme Module Math Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Return x + y End Function End Module End Namespace

In this situation, the function Add is qualified by the namespace name Acme , but the module name Math is still omitted.

The one situation in which a module's name should be used is when two modules define members with the same name. For example:

Module Test Sub Main() Console.WriteLine(Add(10, 20)) End Sub End Module Module IntegerMath Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Return x + y End Function End Module Module LongMath Function Add(ByVal x As Long, ByVal y As Long) As Long Return x + y End Function End Module

In this example, the call to Add is ambiguous ”is the code intended to call IntegerMath.Add or LongMath.Add ? It's not clear. To resolve the ambiguity, Add must be qualified with the name of the module that the method wants to call.

Advanced

When a program is compiled, modules are defined as types in the assembly. To the Framework, a module is equivalent to a class with a Private constructor and all Shared members.

 <  Day Day Up  >  

Категории