如何在一个类中存储变量以供每个类使用

本文关键字:变量 存储 一个 | 更新日期: 2023-09-27 18:00:28

所以我几天前开始学习c#,并开始制作一个简单的乘法器程序:

using System; 
namespace learning_the_syntax
{
    public class GlobalVariables //this class stores all global variables i want to use. Local variables will be stored inside their function/method
    {
        int num01;
        int num02;
    }
    class MainClass
    {
         public static void Main(string[] args)  //This is a function/method named "Main". It is called when the program starts.
         {
             Console.WriteLine("Type a number to be multipied: ");
             num01 = Console.ReadLine();

         }
    }
}

我创建了一个公共类来存储全局变量,但当我尝试在Main类中使用变量num01时,它显示了一条错误消息,指出num01在其当前上下文中不存在。有人能帮忙吗?非常感谢。

如何在一个类中存储变量以供每个类使用

为了访问类之外的成员,您必须将它们声明为public,因此您将具有:

public int num01;
public int num02;

如果你想让程序中的变量是全局的,你应该考虑让它们成为静态的:

public static int num01;
public static int num02;

然后您可以使用以下语法访问它们:

GlobalVariables.num01;
GlobalVariables.num01;