繁体   English   中英

C#类变量初始化

[英]C# class variable initialization

我想声明和初始化一个类本地的字符串变量,但是可以由该类的所有函数访问。 Fyi,这是一个用于gui的应用程序,它将使用文件夹中的多个文本文件。 我试图设置一个包含项目目录路径的字符串变量,以便此类中的所有函数都可以访问它。

我提供了代码的一部分,包括设置路径的函数以及在设置时使用字符串变量的函数。

public class Program
{   
    private string DirectoryPath;

    public static void Main()
    {
        setPaths();
        SetGroundTempArray();
    }

    public static void setPaths()
    {
        DirectoryPath = Directory.GetCurrentDirectory();
    }

    public static void SetGroundTempArray()
    {
        string groundtempfile = "\\groundtemp.txt";
        string groundtempdir = "\\Text Files";
        string groundtempFP = DirectoryPath + groundtempdir + groundtempfile;
    }
}

您的代码将无法编译。
您应该将DirectoryPath类字段声明为静态:

private static string DirectoryPath;

因此,您目前处在正确的轨道上。 在C#中,我们称它们为Fields

字段通常存储必须由多个类方法访问的数据,并且必须存储的时间长于任何单个方法的生存期

在您的情况下, private string DirectoryPath; 是一个领域。 而且您正在遵循将其private的良好做法。

另外,如前所述,您将所有方法都设为static因此还需要使Field变量也变为static变量才能访问它

private static string DirectoryPath;

可以选择将字段声明为静态。 即使该类的实例不存在,这也可以使该字段随时可供调用者使用。

如您的示例中所给出的,您已经正确完成了所需的功能。 但是您可能需要了解有关C#中static关键字用法的更多信息。 您可以在MSDN上了解有关它的更多信息。

这是关于您的代码的一段截距,可能会清除您的概念。
由于您的程序中的静态方法使用DirectoryPath ,因此还必须将这个变量声明为static因为setPaths方法用于静态Main中,并且Main是最顶层的静态类,不需要将实例作为实例。创建的Program类。 这就是为什么Main方法要求所有方法或变量或正在使用的字段必须声明为静态的原因。

public class Program
{   
    private static string DirectoryPath;

    public static void Main()
    {
        setPaths();
        SetGroundTempArray();
    }

    public static void setPaths()
    {
        DirectoryPath = Directory.GetCurrentDirectory();
    }

    public static void SetGroundTempArray()
    {
        string groundtempfile = "\\groundtemp.txt";
        string groundtempdir = "\\Text Files";
        string groundtempFP = DirectoryPath + groundtempdir + groundtempfile;
    }
}

在字符串前面添加static。

 class Program
{
    //add static in front of string
    static String a = "Hello";


    static void Main(string[] args)
    {
        h();
        Console.ReadKey();
    }

    public static void h()
    {
        Console.WriteLine(a);
    }


}

暂无
暂无

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

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