我想知道如何访问Program
控制台应用程序类中的公共变量。
class Program
{
public static string Name { get; set; }
static void Main(string[] args)
{
// Some code here
}
}
static class Settings
{
static public void DoJob()
{
// Access Name of Program ?
}
}
当然,您可以做到这一点,但是,它args
是一个字符串数组,而属性Name
是一个字符串变量,因此您需要将args中的一个值分配给Name。或用于使用定界符String.Join
获取所有值Name
。
由于Name是静态变量,因此无需实例即可访问该变量。您将Program.Name
在静态类中获得该值。现在查看代码:
在Main从args到Name中获取值
public static string Name { get; set; }
static void Main(string[] args)
{
Name = args[0]; // taking the First value from the args array
//or use String.Join to get all elements from args
string delemitter = "";
Name = String.Join(delemitter, args);
}
在静态类中,将Name的值分配给局部变量:
static class Settings
{
static public void DoJob()
{
string localVar = Program.Name;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句