ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Using Multiple Variables with the Same Name

Using Multiple Variables with the Same Name

原创 Linux操作系统 作者:ljm0211 时间:2012-07-02 10:52:13 0 删除 编辑
   If public variables in different modules share the same name, it's possible to differentiate between them in code by referring to both the module and variable names. For example, if there is a public Integer variable intX declared in both Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX to get the correct values.

To see how this works, insert two standard modules in a new project and draw three command buttons on a form.

One variable, intX, is declared in the first standard module, Module1. The Test procedure sets its value:

Public intX As Integer ' Declare Module1's intX.
Sub Test()
' Set the value for the intX variable in Module1.
intX = 1
End Sub

The second variable, which has the same name, intX, is declared in the second standard module, Module2. Again, a procedure named Test sets its value:

Public intX As Integer ' Declare Module2's intX.
Sub Test()
' Set the value for the intX variable in Module2.
intX = 2
End Sub

The third intX variable is declared in the form. module. And again, a procedure named Test sets its value.

Public intX As Integer ' Declare the form's intX
' variable.
Sub Test()
' Set the value for the intX variable in the form.
intX = 3
End Sub

Each of the three command buttons' Click event procedures calls the appropriate Test procedure and uses MsgBox to display the values of the three variables.

Private Sub Command1_Click()
Module1.Test ' Calls Test in Module1.
MsgBox Module1.intX ' Displays Module1's intX.
End Sub

Private Sub Command2_Click()
Module2.Test ' Calls Test in Module2.
MsgBox Module2.intX ' Displays Module2's intX.
End Sub

Private Sub Command3_Click()
Test ' Calls Test in Form1.
MsgBox intX ' Displays Form1's intX.
End Sub

Run the application and click each of the three command buttons. You'll see the separate references to the three public variables. Notice in the third command button's Click event procedure, you don't need to specify Form1.Test when calling the form's Test procedure, or Form1.intX when calling the value of the form's Integer variable. If there are multiple procedures and variables with the same name, Visual Basic takes the value of the more local variable, which in this case, is the Form1 variable.

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11411056/viewspace-734287/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2009-05-14

  • 博文量
    272
  • 访问量
    436869