如何在 Visual Basic 中声明全局变量? [英] How would I declare a global variable in Visual Basic?
问题描述
我想创建一个可以跨多种表单使用的变量.
I want to create a variable that can be used across multiple forms.
它将成为整数的临时存储位置.
It's going to be a temporary storage place for integers.
推荐答案
在 VB 中有几种方法可以做到这一点:一种 VB 特定的方式和一种非 VB 特定的方式(即也可以在C#.
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#.
VB特有的方式是创建一个模块并将变量放在模块中:
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
非 VB 特定的方法是创建一个具有共享属性的类:
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.
假设您始终使用相同的命名空间,则特定于 VB 的方式允许您在没有类限定符的情况下访问变量:
Assuming you are using the same namespace throughout, the VB-specific way allows you to access the variable without a class qualifier:
MyGlobalString = "Test"
对于非 VB 特定的方式,您必须在全局变量前面加上类:
For the non-VB-specific way, you must prefix the global variable with the class:
GlobalVariables.MyGlobalString = "Test"
虽然比较冗长,但我强烈推荐非 VB 特定的方式,因为如果您想将代码或技能集转换为 C#,VB 特定的方式是不可移植的.
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.
这篇关于如何在 Visual Basic 中声明全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!