我想声明并初始化一个字符串变量,该变量是类的本地变量,但该类的所有函数都可以访问。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
类字段声明为static:
private static string DirectoryPath;
所以您目前正处于正确的轨道上。在C#中,我们称它们为字段
字段通常存储的数据必须可访问一个类方法,并且存储的时间必须长于任何单一方法
在您的情况下,private string DirectoryPath;
是一个字段。您正在遵循使其成为private
的良好做法。
此外,如前所述,所有方法都是static
,因此您需要使字段变量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);
}
}