我的导师给我布置了一个 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();
}
}
最佳答案
C# 没有全局变量的特定概念,但您可以使用公共(public)静态属性或字段实现效果,然后通过类访问它们。例如:
public class GlobalVariables
{
public static double TaxRate {get; set;}
}
访问 GlobalVariabels.TaxRate
。
public允许我们从类外部访问变量。 static意味着我们不需要 GlobalVariables
类的实例来访问它(尽管您确实需要在类的上下文之外遍历类名。
作为Preston指出,您可以将 GlobalVariables 类设为静态,因为实际上没有任何理由实例化它的实例(尽管这不是必需的)。
关于c# - 我可以在我的 C# 程序中的什么地方使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28465045/