0

我正在开发一个愚蠢的小终端应用程序,它显示当前时间以及用户下班的时间。我有一个小问题。在“工作退出时间”是静态的之前,我将其设置为下午 6:00:00,我试图接受它并允许用户输入主题。现在我的代码可以获取变量集。但是我不能将它 [WorkOut 的变量] 放在我想要它去的地方。

这是我到目前为止所拥有的:

namespace timerconsole
{
    class MainClass
    {
        public void run ()
        {
            int width = 35;
            int height = 10;

            Console.SetWindowPosition(0, 0); 
            Console.SetWindowSize(width, height); 
            Console.SetBufferSize(width, height); 
            Console.SetWindowSize(width, height);
            Console.WriteLine ("What time do you leave work today: ");

            String workTime = Console.ReadLine ();
            int workOut;
            int.TryParse (workTime, out workOut);

            TimerCallback callback = new TimerCallback(Tick);

            // create a one second timer tick
            Timer stateTimer = new Timer(callback, null, 0, 1000);

            // loop here forever
            for (; ; ) { }
        }

        static public void Tick(Object stateInfo)
        {
            Console.Clear ();
            Console.WriteLine("The time is: {0}", DateTime.Now.ToString("h:mm:ss") + "\nWork Target: {0}", workOut); // workOut is my issue. It says "workOut does not exist in current context"
        }

        public static void Main (string[] args)
        {
            MainClass tc = new MainClass ();
            tc.run ();
        }
    }
}
4

1 回答 1

2

您定义workOut为范围内的整数run()。它不存在于该方法之外,更不用说静态方法可以访问了。尝试将定义移到方法workOut之外run并将其声明为static.

namespace timerconsole
{
    class MainClass
    {
        static int workOut; /* Here */

        public void run ()
        {
            int width = 35;
            int height = 10;

            Console.SetWindowPosition(0, 0); 
            Console.SetWindowSize(width, height); 
            Console.SetBufferSize(width, height); 
            Console.SetWindowSize(width, height);


            Console.WriteLine ("What time do you leave work today: ");

            String workTime = Console.ReadLine ();

            int.TryParse (workTime, out workOut);

            TimerCallback callback = new TimerCallback(Tick);

            // create a one second timer tick
            Timer stateTimer = new Timer(callback, null, 0, 1000);

            // loop here forever
            for (; ; ) { } /* You may want to use Thread.Sleep to not consume *all* of the CPU */
        }

        static public void Tick(Object stateInfo)
        {
            Console.Clear ();
            Console.WriteLine("The time is: {0}", DateTime.Now.ToString("h:mm:ss") + "\nWork Target: {1}", workOut);
        }

        public static void Main (string[] args)
        {
            MainClass tc = new MainClass ();
            tc.run ();
        }
    }
}
于 2013-05-23T17:55:13.253 回答