如何在每个类中使用变量存储?

时间:2015-06-29 21:08:04

标签: c#

所以我几天前开始学习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();



         }
    }

}

我创建了一个公共类来存储我的全局变量但是当我尝试在我的num01类中使用变量Main时,它会显示一条错误消息,指出num01不存在在目前的背景下。有人可以帮忙吗?谢谢。

1 个答案:

答案 0 :(得分:0)

要访问课程外的成员,您必须将其声明为公开,因此您将拥有:

public int num01;
public int num02;

如果您希望变量在程序中是全局变量,您应该考虑将它们设置为静态变量:

public static int num01;
public static int num02;

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

GlobalVariables.num01;
GlobalVariables.num01;