是否可以在程序中以任何形式访问布尔值/字符串/整数/等

本文关键字:布尔值 字符串 整数 访问 任何形 程序 是否 | 更新日期: 2023-09-27 18:35:52

我对全局变量做了一些研究,并提出了静态变量应该能够解决我的问题的事实。不过,我不明白如何制作这些。我该怎么做?另外,如果静态变量不能解决我的问题,我应该使用什么?

我希望能够从另一种形式访问主窗体中的字符串、bool 和 int。帮助?

是否可以在程序中以任何形式访问布尔值/字符串/整数/等

静态变量(或者更好的是属性)可能会起作用。 您可以将其声明为:

// In Form1 (could be internal or public)
public static bool SomeBool { get; set; }

然后,要访问,您将使用 Form1.SomeBool = true;if (Form1.SomeBool) { ,等等。

话虽如此,不鼓励使用这样的"全球"数据是有原因的 - 通常有一些更好的方法来处理这个问题。 例如,您可能希望创建一个保存数据的自定义类,并在创建此类实例时将对该类实例的引用传递给新窗体。

不仅是静态的,还必须是public static的。 您可以像任何其他变量一样简单地声明它,如 public static int x = 1; .然后你可以像ClassFoo.x一样访问它,但你也必须处于静态上下文中。

如果您希望按表单实例(对象)保存此信息,则不希望使用静态字段。另一方面,如果您想要的是拥有一些可以从类形式的任何实例(它是共享的)访问的信息,或者换句话说,您希望仅拥有一次此信息......那么是的,使用静态字段。

你想要做的是这样的:

//partial because I take you are using a form designer.
//and also because the class is gonna have more things than those showed here.
//in particular the example call a method "UseFields" that I did not define.
public partial class MyForm: form
{
    private static bool boolField;
    private static string stringField;
    private static int intField;
    private void Method()
    {
         //Do something with the fields
         UseFields(boolField, stringField, intField);
         UseFields(IsBoolFieldSet, SomeString, SharedInformation.SomeInt);
    }
    //You can also wrap them in a property:
    public static bool IsBoolFieldSet
    {
        get
        {
            return boolField;
        }
        //Don't put a set if you want it to be read only
        set
        {
            return boolField;
        }
    }
    //Or declare an static property like so:
    public static string SomeString { get; set; }
}
//Another good option is to have this information in a separate class
public class SharedInformation
{
    public static int SomeInt { get; set; }        
}

请注意共享状态,尤其是在多线程环境中,因为此信息可能会被另一个具有访问权限的对象更改,恕不另行通知。