在 Visual Studio 2010 和 VB.NET 中声明全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4529862/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:13:04  来源:igfitidea点击:

Declare global variables in Visual Studio 2010 and VB.NET

vb.netglobal-variables

提问by Tal

How do I declare a global variable in Visual Basic?

如何在 Visual Basic 中声明全局变量?

These variables need to be accessible from all the Visual Basic forms. I know how to declare a public variable for a specific form, but how do I do this for all the forms in my project?

这些变量需要可从所有 Visual Basic 窗体访问。我知道如何为特定表单声明公共变量,但如何为项目中的所有表单执行此操作?

回答by Cody Gray

There is no way to declare global variables as you're probably imagining them in VB.NET.

没有办法声明全局变量,因为您可能在 VB.NET 中想象它们。

What you cando (as some of the other answers have suggested) is declare everything that you want to treat as a global variable as static variables instead within one particular class:

可以做的(正如其他一些答案所建议的那样)是将您想要视为全局变量的所有内容声明为静态变量,而不是在一个特定类中:

Public Class GlobalVariables
    Public Shared UserName As String = "Tim Johnson"
    Public Shared UserAge As Integer = 39
End Class

However, you'll need to fully-qualify all references to those variables anywhere you want to use them in your code. In this sense, they are not the type of global variables with which you may be familiar from other languages, because they are still associated with some particular class.

但是,您需要完全限定对这些变量的所有引用,只要您想在代码中使用它们。从这个意义上说,它们不是您在其他语言中可能熟悉的全局变量类型,因为它们仍然与某个特定类相关联。

For example, if you want to display a message box in your form's code with the user's name, you'll have to do something like this:

例如,如果您想在表单代码中显示一个带有用户名的消息框,您必须执行以下操作:

Public Class Form1: Inherits Form

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        MessageBox.Show("Hello, " & GlobalVariables.UserName)
    End Sub

End Class

You can't simply access the variable by typing UserNameoutside of the class in which it is defined—you must also specify the name of the class in which it is defined.

不能简单地通过在定义变量UserName的类之外键入来访问变量——还必须指定定义变量的类的名称。


If the practice of fully-qualifying your variables horrifies or upsets you for whatever reason, you can always import the class that contains your global variable declarations (here, GlobalVariables) at the top of each code file (or even at the project level, in the project's Properties window). Then, you could simply reference the variables by their name.


如果完全限定变量的做法无论出于何种原因使您感到恐惧或不安,您始终可以GlobalVariables在每个代码文件的顶部(甚至在项目级别,在项目的属性窗口)。然后,您可以简单地通过名称引用变量。

Imports GlobalVariables

Note that this is exactlythe same thing that the compiler is doing for you behind-the-scenes when you declare your global variables in a Module, rather than a Class. In VB.NET, which offers modules for backward-compatibility purposes with previous versions of VB, a Moduleis simply a sealed static class (or, in VB.NET terms, Shared NotInheritable Class). The IDE allows you to call members from modules without fully-qualifying or importing a reference to them. Even if you decide to go this route, it's worth understanding what is happening behind the scenes in an object-oriented language like VB.NET. I think that as a programmer, it's important to understand what's going on and what exactly your tools are doing for you, even if you decide to use them. And for what it's worth, I do not recommend this as a "best practice" because I feel that it tends towards obscurity and clean object-oriented code/design. It's much more likely that a C# programmer will understand your code if it's written as shown above than if you cram it into a module and let the compiler handle everything.

请注意,当您在 a而不是 a 中声明全局变量时,这与编译器在幕后为您做的事情完全相同。在 VB.NET 中,它提供了用于与以前版本的 VB 向后兼容的模块,a只是一个密封的静态类(或者,在 VB.NET 术语中,ModuleClassModuleShared NotInheritable Class)。IDE 允许您从模块调用成员,而无需完全限定或导入对它们的引用。即使您决定走这条路,也值得了解在面向对象的语言(如 VB.NET)中幕后发生的事情。我认为,作为一名程序员,了解正在发生的事情以及您的工具究竟为您做什么是很重要的,即使您决定使用它们。就其价值而言,我不建议将此作为“最佳实践”,因为我觉得它倾向于晦涩难懂和干净的面向对象的代码/设计。如果您的代码如上所示编写,则 C# 程序员更有可能理解您的代码,而不是将其塞入模块并让编译器处理所有内容。


Note that like at least one other answer has alluded to, VB.NET is a fully object-oriented language. That means, among other things, that everythingis an object. Even "global" variables have to be defined within an instance of a class because they are objects as well. Any time you feel the need to use global variables in an object-oriented language, that a sign you need to rethink your design. If you're just making the switch to object-oriented programming, it's more than worth your while to stop and learn some of the basic patterns before entrenching yourself any further into writing code.


请注意,就像至少一个其他答案所提到的那样,VB.NET 是一种完全面向对象的语言。这意味着,除其他外,一切都是对象。甚至“全局”变量也必须在类的实例中定义,因为它们也是对象。任何时候您觉得需要在面向对象的语言中使用全局变量,这都表明您需要重新考虑您的设计。如果您只是转向面向对象编程,那么在进一步深入编写代码之前停下来学习一些基本模式是非常值得的。

回答by RBarryYoung

Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:

与您一直使用的方式几乎相同,使用“模块”而不是类,只需使用“公共”而不是旧的“全局”关键字:

Public Module Module1
    Public Foo As Integer
End Module

回答by JSS

Okay. I finallyfound what actually works to answer the question that seems to be asked;

好的。我终于找到了实际上可以回答似乎被问到的问题的方法;

"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"

“当需要许多模块和表单时,我如何声明一个变量对所有模块和表单都是公开的,以便它们每个都引用相同的变量?”

Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.

令我惊讶的是,我花了大量时间在网上搜索这个看似简单的问题,发现除了含糊不清的内容外,什么也没找到,这让我仍然遇到错误。

But thanks to Cody Gray's link to an example, I was able to discern a proper answer;

但是多亏了 Cody Gray 的示例链接,我才能够辨别出正确的答案;



Situation; You have multiple Modules and/or Forms and want to reference a particular variable from each or all.

情况;您有多个模块和/或表单,并且想要从每个或所有引用一个特定变量。

"A" way that works; On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);

“一种”有效的方式;在一个模块上放置以下代码(其中“DefineGlobals”是一个任意选择的名称);

Public Module DefineGlobals

Public Parts As Integer                 'Assembled-particle count
Public FirstPrtAff As Long              'Addr into Link List 
End Module

And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);

然后在每个需要寻址变量“Parts”的Module/Form中,放置以下代码(以“InitForm2”表单为例);

Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Parts = Parts + 3

End Sub

End Class

And perhaps another Form; Public Class FormX

也许是另一种形式;公开课 FormX

Sub CreateAff()

   Parts = 1000

End Sub 

 End Class

That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.

这种类型的编码似乎已经在我的 VB2008 Express 上工作了,并且目前似乎是需要的(没有在后台加载任何未知文件),即使我发现“哦顺便说一句......”的惊喜没有尽头细节。而且我确信更高程度的标准化将是首选,但首要任务只是让某些东西完全正常工作,无论是否有标准。

Nothing beats exact and well worded, explicitexamples.

没有什么比准确、措辞准确、明确的例子更胜一筹了

Thanks again, Cody

再次感谢,科迪

回答by Jürgen Steinblock

Make it static (shared in VB).

将其设为静态(在 VB 中共享)。

Public Class Form1

   Public Shared SomeValue As Integer = 5

End Class

回答by Oded

Public variables are a code smell - try to redesign your application so these are notneeded. Most of the reasoning hereand hereare as applicable to VB.NET.

公共变量是一个代码味道-尝试重新设计应用程序,以便它们不会需要。这里这里的大部分推理都适用于 VB.NET。

The simplest way to have global variables in VB.NET is to create public static variables on a class (declare a variable as Public Shared).

在 VB.NET 中拥有全局变量的最简单方法是在类上创建公共静态变量(将变量声明为Public Shared)。

回答by Check-Kay Wong

A global variable could be accessible in all your forms in your project if you use the keyword public sharedif it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.

public shared如果在类中使用关键字,则可以在项目中的所有表单中访问全局变量。如果您在模块下使用关键字“public”,它也会起作用,但由于多种原因,这不是最佳实践。

(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)

(……是的,我有点重复“Cody Gray”和“RBarryYoung”所说的话。)

One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NETand download the sample project!

问题之一是当您有两个线程同时调用同一个全局变量时。你会有一些惊喜。如果您不知道它们的局限性,您可能会有意想不到的反应。查看Visual Basic .NET 中的全局变量一文并下载示例项目!

回答by Smart Thinker

small remark: I am using modules in webbased application (asp.net). I need to remember that everything I store in the variables on the module are seen by everyone in the application, read website. Not only in my session. If i try to add up a calculation in my session I need to make an array to filter the numbers for my session and for others. Modules is a great way to work but need concentration on how to use it.

小备注:我在基于 web 的应用程序 (asp.net) 中使用模块。我需要记住,我存储在模块变量中的所有内容都可以被应用程序中的每个人看到,阅读网站。不仅在我的会话中。如果我尝试在我的会话中添加一个计算,我需要创建一个数组来过滤我的会话和其他会话的数字。模块是一种很好的工作方式,但需要专注于如何使用它。

To help against mistakes: classes are send to the

为了帮助避免错误:课程被发送到

CarbageCollector

垃圾收集器

when the page is finished. My modules stay alive (as long as the application is not ended or restarted) and I can reuse the data in it. I use this to save data that sometimes is lost because of the sessionhandling by IIS.

当页面完成时。我的模块保持活动状态(只要应用程序没有结束或重新启动)并且我可以重用其中的数据。我用它来保存有时由于 IIS 的会话处理而丢失的数据。

IIS Form auth

IIS 表单身份验证

and

IIS_session

IIS_session

are not in sync, and with my module I pull back data that went over de cliff.

不同步,我用我的模块拉回了悬崖上的数据。

回答by user2366092

All of above can be avoided by simply declaring a friend value for runtime on the starting form.

以上所有情况都可以通过简单地在起始表单上声明运行时的友元值来避免。

Public Class Form1 
Friend sharevalue as string = "Boo"

Then access this variable from all forms simply using Form1.sharevalue

然后简单地使用从所有形式访问这个变量 Form1.sharevalue

回答by 2zoo

You could just add a new Variable under the properties of your project Each time you want to get that variable you just have to use

您可以在项目的属性下添加一个新变量每次您想要获取该变量时,您只需要使用

My.Settings.(Name of variable)

That'll work for the entire Project in all forms

这将适用于所有形式的整个项目

回答by JSS

None of these answers seem to be changing anything for me.

这些答案似乎都没有改变我的任何东西。

I am converting an old Excel program to VB 2008. Of course, there are many Excel specific things to change, but something that is causing a headache seems to be this whole "Public" issue.

我正在将一个旧的 Excel 程序转换为 VB 2008。当然,有许多 Excel 特定的东西要更改,但令人头疼的似乎是整个“公共”问题。

I have about 40 arrays all being referenced by about 20 modules. The arrays form the foundation of the entire project and are addressed by just about every procedure.

我有大约 40 个数组都被大约 20 个模块引用。数组构成了整个项目的基础,几乎每个过程都涉及到这些数组。

In Excel, I simply had to declare them all as Public. Worked great. No problem. But in VB2008, I'm finding it quite an issue. It is absurd to think that I have to go through thousands of lines of code merely to tell each reference where the Public has been declared. But even willing to do that, none of the schemes being proposed seems to help at all.

在 Excel 中,我只需将它们全部声明为 Public。工作得很好。没问题。但是在 VB2008 中,我发现这是一个很大的问题。认为我必须通过数千行代码只是为了告诉每个引用在何处声明了 Public 是荒谬的。但即使愿意这样做,提议的计划似乎都没有帮助。

It appears that "Public" merely means "Public within this one module". Adding "Shared" seems to do nothing to change that. Adding the module name or anything else doesn't seem to change that. Each module insists that I declare all arrays (and about 100 other fundamental variables) within each module (a seemingly backward advance). And the "Imports" bit doesn't seem to know what I am talking about either, "cannot be found".

似乎“公共”仅意味着“在这个模块中公共”。添加“共享”似乎无济于事。添加模块名称或其他任何内容似乎都不会改变。每个模块都坚持我在每个模块中声明所有数组(以及大约 100 个其他基本变量)(看似向后推进)。而“进口”位似乎也不知道我在说什么,“找不到”。

I have to sympathize with the questioner. Something seems terribly amiss with all of this.

我不得不同情提问者。这一切似乎有些不对劲。