简体   繁体   English

c# 等价于 VB6 公共变量

[英]c# Equivalent to VB6 Public variable

Suppose I my project contains a Form and a Class.假设我的项目包含一个表格和一个 Class。 I would like to create a variable that can be accessed by both the Form and the class.我想创建一个可以由 Formclass 访问的变量。 In VB6 I could create a public variable in the (module / class), and easily access it like so:在 VB6 中,我可以在(模块/类)中创建一个公共变量,并像这样轻松访问它:

VB6 Example VB6 示例

[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#?如何使用 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.我假设我必须创建一个公共 class,但我不确定声明公共变量的最佳方式。

thank you,谢谢你,

Evan埃文

You can create a public static class with a public static variable.您可以使用公共 static 变量创建public static class

public static class MyPublicData
{

    public static string MyData1 = "My public data";

}

To use:要使用:

var x = MyPublicData.MyData1;

You can do the same in c# (expose a field as public), though that is not good practice.您可以在 c# 中执行相同的操作(将字段公开为公共),但这不是好的做法。

Use properties instead:改用属性:

// public string property
public string string_name { get; set; }

// within class    
string_name = "test data";
MsgBox(string_name); 

// from another class
myClassInstance.string_name = "other test data";
public class MyClass
{
  public int MyPublicVariable;
  public int MyPublicProperty {get; set; }
}

Try a public class with a public static variable.尝试使用公共 class 和公共 static 变量。 Example:例子:

public class PortalResources
    {
        #region Members

        public enum Mode 
        {
            LargeIconMode,
            SmallIconMode, 
            DetailsMode
        };

        public static int LargeIconSize = 150;
        public static int SmallIconSize = 75;
        public static string Name = "Name";

        #endregion

    }

Usage:用法:

int IconSize = PortalResources.LargeIconSize;
int ViewMode = PortalResources.Mode.LargeIconMode;

The equivalent of a VB public (or global) variable is a public static property on a class. VB 公共(或全局)变量的等效项是 class 上的公共 static 属性。

You have to specify您必须指定

Classname.PropertyName

To access it, though.不过,要访问它。

If you need the value to be a constant or static readonly value then place it in a static class:如果您需要该值是常量或 static 只读值,则将其放入 static class 中:

public class Globals
{
    public const String value = "Hello World";
}

public static class Globals
{
    public static value2 = "Hello World";
}

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.如果该值只需要可访问(不是只读的),那么您最好将此值粘贴在设置文件中并获取设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM