c# - 我可以在我的 C# 程序中的什么地方使用全局变量?

标签 c# .net 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();
    }
}

最佳答案

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/

相关文章:

c# - 如何将 2 个 zip 文件合并为 1 个?

c# - 查看项目/解决方案的所有项目引用的工具

variables - Lua 函数选择局部变量而不是全局变量

c# - 如何将泛型类序列化为 XML?

c# - 嵌套开关表达式

c# - 为什么我的 TCP 应用程序在快速发送时会丢失一些数据包

c# - 从 csv 文件读取并在 .net 中处理它

c# - Web API 请求的滑动 session

global-variables - 从 Julia 中的另一个模块更改全局变量的内容

java - C++/Java递归变量初始化