vb.net 如何在 Visual Basic 中创建全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17255847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a global variable in Visual Basic
提问by dei.andrei98
I have a Mysql login system in Visual Basic , and I want to store the username in a global variable after a succesful login but when the app will close I want that variable to be deleted.. can you show me some example? I'm a beginner at visual basic.
我在 Visual Basic 中有一个 Mysql 登录系统,我想在成功登录后将用户名存储在全局变量中,但是当应用程序关闭时,我希望删除该变量..你能给我举一些例子吗?我是视觉基础的初学者。
回答by Bathsheba
If you're developing on Windows, then use the Windows Registry to persist the value.
如果您在 Windows 上进行开发,则使用 Windows 注册表来保留该值。
See http://msdn.microsoft.com/en-us/library/aa289494(v=vs.71).aspxfor more details, and examples.
有关更多详细信息和示例,请参阅http://msdn.microsoft.com/en-us/library/aa289494(v=vs.71).aspx。
Take care if caching a password though; you'll need to encrypt that.
如果缓存密码,请小心;你需要加密。
回答by Manny265
Just create a class (in your project) that will not be instantiated right...and then have a variable in that class with access modifier
Public Shared.
Like for me I made a class called Globals and in it was a variable called currentUser .
So to access the variable from any class I just had Globals.currentUser =txtUser.Text
And declare it like Public Shared currentUser as String
只需创建一个不会被正确实例化的类(在您的项目中)......然后在该类中使用访问修饰符Public Shared的变量
。
对我来说,我创建了一个名为 Globals 的类,其中有一个名为currentUser的变量。
所以要从任何类访问变量,我只有Globals.currentUser =txtUser.Text
并将其声明为Public Shared currentUser as String
回答by tinstaafl
Try this, in your form file outside of the main class, or in a separate module file:
在主类之外的表单文件中或在单独的模块文件中试试这个:
Public Module Globals
Public UserName As String = ""
End Module
Now you can access it in any code throughout your project. It will dispose when the app is closed. If you wanted to make doubly sure, even though it would be redundant, add this to the main form that closes the whole app:
现在,您可以在整个项目中以任何代码访问它。它将在应用程序关闭时处理。如果您想加倍确定,即使它是多余的,请将其添加到关闭整个应用程序的主窗体中:
Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
UserName = ""
End Sub

