Chr*_*yer 1 .net c# global-variables
我的导师为我设定了制作C#程序的任务
这就是我想出来的.它只需要是一个小程序,但我不知道在哪里可以使用全局变量.我在考虑减税,但每次开始我都会忘记我的想法.
static void nameCheck()
{
Console.WriteLine("Name of employee: ");
string employee = Console.ReadLine();
string[] employees = { "Emp1", "Emp2", "Emp3", "Emp4" };
File.WriteAllLines("C:/Users/Chris/Documents/Visual Studio 2013/Projects/ConsoleApplication38/Employees.txt", employees);
string[] lines = File.ReadAllLines("C:/Users/Chris/Documents/Visual Studio 2013/Projects/ConsoleApplication38/Employees.txt");
int match = 0;
foreach (string line in lines)
{
if (employee != line)
{
match = match + 1;
if (match > 3)
{
Console.WriteLine("That name is not in the employee database, try again:");
nameCheck();
}
}
}
}
static double payRoll(double hours, double wage)
{
double pay = hours * wage;
return pay;
}
static void Main(string[] args)
{
Console.WriteLine(" PAYROLL");
Console.WriteLine("--------------------------------------------------------------------------------");
nameCheck();
Console.WriteLine("Number of hours worked this week: ");
int hours = Convert.ToInt32(Console.ReadLine());
const double wage = 7.50;
double pay = payRoll(hours, wage);
Console.WriteLine("Pay before tax for this employee is £" + pay);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
C#没有全局变量的特定概念,但您可以使用公共静态属性或字段实现该效果,然后可以通过该类访问.例如:
public class GlobalVariables
{
public static double TaxRate {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
访问时间GlobalVariabels.TaxRate.
public允许我们从类外部访问变量.static意味着我们不需要GlobalVariables类的实例来访问它(尽管你需要在类的上下文之外查看类名.
正如普雷斯顿指出的那样,你可以使你的GlobalVariables类保持静态,因为没有任何理由来实例化它的实例(虽然没有必要).