c# 相当于 VB6 公共变量
假设我的项目包含一个表单和一个类。我想创建一个可以由表单和类访问的变量。在 VB6 中,我可以在(模块/类)中创建一个公共变量,并轻松访问它,如下所示:
VB6 示例
[Module code]
Public string_name as string
[/Module code]
[Form Code]
string_name = "test data"
MsgBox(string_name) ' Returns "test data"
[/Form Code]
如何使用 C# 生成上述功能?我假设我必须创建一个公共类,但我不确定声明公共变量的最佳方法。
谢谢你,
埃文
Suppose I my project contains a Form and a Class. I would like to create a variable that can be accessed by both the Form and the class. In VB6 I could create a public variable in the (module / class), and easily access it like so:
VB6 Example
[Module code]
Public string_name as string
[/Module code]
[Form Code]
string_name = "test data"
MsgBox(string_name) ' Returns "test data"
[/Form Code]
How could I produce the above functionality with C#? I'm assuming I'd have to create a public class, but I'm not sure of the best way to declare public variables.
thank you,
Evan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用公共静态变量创建一个
公共静态类
。使用方法:
You can create a
public static class
with a public static variable.To use:
您可以在 C# 中执行相同的操作(将字段公开为公共字段),但这不是一个好的做法。
使用属性代替:
You can do the same in c# (expose a field as public), though that is not good practice.
Use properties instead:
VB 公共(或全局)变量的等价物是类的公共静态属性。
不过,您必须指定
要访问它。
The equivalent of a VB public (or global) variable is a public static property on a class.
You have to specify
To access it, though.
尝试使用公共静态变量的公共类。示例:
用法:
Try a public class with a public static variable. Example:
Usage:
如果您需要该值是常量或静态只读值,则将其放入静态类中:
如果该值只需要可访问(而不是只读),那么您最好将此值粘贴在设置文件中并获取环境。
If you need the value to be a constant or static readonly value then place it in a static class:
If the value just needs to be accessible (not readonly), then you're better off sticking this value in a settings file and grabbing the setting.