How would I declare a global variable in Visual Basic?

前端 未结 3 1978
逝去的感伤
逝去的感伤 2021-01-04 23:08

I want to create a variable that can be used across multiple forms.

It\'s going to be a temporary storage place for integers.

3条回答
  •  鱼传尺愫
    2021-01-04 23:42

    There are a couple of ways to do this in VB: a VB-specific way and a non-VB specific way (i.e. one that could also be implemented in C#.

    The VB-specific way is to create a module and place the variable in the module:

    Public Module GlobalVariables
       Public MyGlobalString As String
    End Module
    

    The non-VB-specific way is to create a class with shared properties:

    Public Class GlobalVariables
      Public Shared Property MyGlobalString As String
    End Class
    

    The primary difference between the two approaches is how you access the global variables.

    Assuming you are using the same namespace throughout, the VB-specific way allows you to access the variable without a class qualifier:

    MyGlobalString = "Test"
    

    For the non-VB-specific way, you must prefix the global variable with the class:

    GlobalVariables.MyGlobalString = "Test"
    

    Although it is more verbose, I strongly recommend the non-VB-specific way because if you ever want to transition your code or skillset to C#, the VB-specific way is not portable.

提交回复
热议问题