在我的c#程序中哪里可以使用全局变量?

在我的c#程序中哪里可以使用全局变量?,c#,.net,global-variables,C#,.net,Global Variables,我的导师让我做一个C#程序 演示递归(我想我已经做到了) 使用全局变量 可供企业使用 这就是我想到的。它只需要是一个小程序,但我不知道在哪里可以使用全局变量。我本来想做些减税的事情,但每次我一开始就忘了我的想法是什么 static void nameCheck() { Console.WriteLine("Name of employee: "); string employee = Console.ReadLine(); string[] employees =

我的导师让我做一个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 class GlobalVariables
{
    public static double TaxRate {get; set;}
}
访问地址为
GlobalVariabels.TaxRate

允许我们从类外部访问变量。意味着我们不需要
GlobalVariables
类的实例来访问它(尽管您需要在类的上下文之外遍历类名)

正如所指出的,您可以使您的GlobalVariables类成为静态的,因为实际上没有任何理由实例化它的实例(尽管这不是必需的).

C#没有全局变量的特定概念,但您可以使用公共静态属性或字段实现效果,然后通过类访问该属性或字段。例如:

public class GlobalVariables
{
    public static double TaxRate {get; set;}
}
访问地址为
GlobalVariabels.TaxRate

允许我们从类外部访问变量。这意味着我们不需要
GlobalVariables
类的实例来访问它(尽管您需要在类的上下文之外遍历类名)

正如所指出的,您可以使GlobalVariables类成为静态的,因为实际上没有任何理由实例化它的一个实例(尽管它不是必需的)。

C#是一种面向对象的编程语言,这意味着您可以通过一个作为类实现的对象访问所有内容。因此每个变量(这种情况下的成员)是可见的,如果类和成员都是可访问的,可以通过将它们声明为public

C#是一种面向对象的编程语言,这意味着您可以通过作为类实现的对象访问所有内容。因此每个变量(这种情况下的成员)如果类和成员都是可访问的,则可见,这可以通过将它们声明为“全局变量”(引用,因为请参见)的public

来完成。请查找可以从方法中移出的内容

最好的选择是在调用
nameCheck
method-
string[]employees={“Emp1”、“Emp2”、“Emp3”、“Emp4”};
的过程中保持不变的变量

由于您没有发布显示使用多个类的代码,因此将
员工
移出方法是您的最佳选择。如果您已经在课堂上学习了多个类,那么就用在那里学习的内容来组织代码。也可以看一看。

有关您的“全局变量”(请参阅)寻找一些你可以从你的方法中移除的东西

最好的选择是在调用
nameCheck
method-
string[]employees={“Emp1”、“Emp2”、“Emp3”、“Emp4”};
的过程中保持不变的变量

由于您没有发布显示使用多个类的代码,因此将
员工
移出该方法是您的最佳选择。如果您已经在课堂上学习了多个类,那么请使用在那里学习的内容来组织代码。也可以浏览一下。

您也可以使用like

    static double payRoll(double hours, double wage)
    {
        return hours * wage;
    }

你也可以用like

    static double payRoll(double hours, double wage)
    {
        return hours * wage;
    }


我对您的逻辑进行了更改,首先它读取文件一次,检查文件是否存在,否则它将创建文件。添加注释并修复结构,删除不必要的变量,并考虑以前的答案以帮助您

namespace Temp1
{
    using System;
    using System.IO;

    public class GlobalVariables
    {
        /// <summary>
        /// Wage per hour
        /// </summary>
        public static double WagePerHour = 7.5;
    } 

    public class Program
    {
        private static void LoadEmployees()
        {
            // Get the name of the employee
            Console.WriteLine("Name of employee: ");
            string employee = Console.ReadLine();

            // Get the file path
            string filePath = string.Format(
                @"{0}\{1}",
                Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
                "Employees.txt");

            // Check if the file does not exist and create it
            if (!File.Exists(filePath))
            {
                // Generate sample employees
                string[] employees = { "Emp1", "Emp2", "Emp3", "Emp4" };

                // Write all the lines in the file
                File.WriteAllLines(filePath, employees);
            }

            // Read all the lines from the file
            string[] currentEmployees = File.ReadAllLines(filePath);

            // Check the employee name
            NameCheck(currentEmployees, employee);
        }

        /// <summary>
        /// Do the name check recursively so you don’t keep loading the file all the time
        /// </summary>
        /// <param name="names">Array of all the employee names</param>
        /// <param name="nameToFind">Name to find</param>
        /// <param name="currentPosition">Current position in the array</param>
        public static void NameCheck(string[] names, string nameToFind, int currentPosition = 0)
        {
            if (currentPosition == nameToFind.Length - 1)
            {
                Console.WriteLine("That name is not in the employee database, try again:");
            }
            else if (string.Compare(names[currentPosition], nameToFind, StringComparison.InvariantCulture) != 0)
            {
                currentPosition++;
                NameCheck(names, nameToFind, currentPosition);
            }
        }

        /// <summary>
        /// Calculate pay roll
        /// </summary>
        /// <param name="hours"></param>
        /// <param name="wage"></param>
        /// <returns></returns>
        private static double PayRoll(double hours, double wage)
        {
            return hours * wage;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            Console.WriteLine("                                   PAYROLL");
            Console.WriteLine("--------------------------------------------------------------------------------");

            // Load employees and check if the employee is in the list
            LoadEmployees();

            // Get the number of hours worked
            Console.WriteLine("Number of hours worked this week: ");
            double hours = Convert.ToDouble(Console.ReadLine());

            // Get the current pay
            double pay = PayRoll(hours, GlobalVariables.WagePerHour);

            Console.WriteLine("Pay before tax for this employee is £" + pay);
            Console.ReadLine();
        }
    }
}
namespace Temp1
{
使用制度;
使用System.IO;
公共类全局变量
{
/// 
///小时工资
/// 
公共静态双下注/小时=7.5;
} 
公共课程
{
私有静态void LoadEmployees()
{
//获取员工的姓名
Console.WriteLine(“员工姓名:”);
字符串employee=Console.ReadLine();
//获取文件路径
string filePath=string.Format(
@"{0}\{1}",
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutionGassembly().Location),
“Employees.txt”);
//检查文件是否不存在并创建它
如果(!File.Exists(filePath))
{
//生成样本员工
字符串[]employees={“Emp1”、“Emp2”、“Emp3”、“Emp4”};
//写下文件中的所有行
File.writeAllines(文件路径,员工);
}
//读取文件中的所有行
字符串[]currentEmployees=File.ReadAllLines(文件路径);
//检查员工姓名
姓名检查(当前员工、员工);
}
/// 
///递归地进行名称检查,这样就不会一直加载文件
/// 
///所有员工姓名的数组
///要查找的名称
///阵列中的当前位置
公共静态无效名称检查(字符串[]名称,字符串名称查找,int currentPosition=0)
{
如果(currentPosition==nameToFind.Length-1)
{
WriteLine(“该名称不在员工数据库中,请重试:”;
}
else if(string.Compare(名称[currentPosition],名称查找,StringComparison.InvariantCulture)!=0)
{
currentPosition++;
名称检查(名称、名称查找、当前位置);
}
}
/// 
///计算工资表
/// 
///