如何调用"静态主要"中的另一个函数方法?

时间:2014-09-18 05:32:07

标签: c#

我是C#的初学者,我想在SetTimer()中调用一个函数static void Main(),但它在SetTimer(11, 48, 00);SetTimer(11, 35, 40);下面会出现一些错误。实际上,使用Main()函数可以在表单中很好地工作。我对如何以及何时使用这些类型感到困惑:

  • public void
  • static void
  • public static void
  • private static void
  • 空隙

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace SetTimerAlert
{
    public class Program
    {
        int count = 0;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            //Application.Run(new Form1());
            if (rkApp.GetValue("SetTimerAlert") == null)
            {
                Application.Run(new Form1());
            }
            else
            {
                SetTimer(11, 48, 00);
                SetTimer(11, 35, 40);
            }
        }

        public void SetTimer(int hh, int mm, int ss)
        {
            DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hh, mm, ss);
            TimerCallback callback = new TimerCallback(ProcessTimerEvent);

            if (DateTime.Now < dt)
            {
                var timer = new System.Threading.Timer(callback, null,
                    //other occurrences every 24 hours
                                dt - DateTime.Now, TimeSpan.FromHours(24));
            }
        }

        public void ProcessTimerEvent(object obj)
        {
            if (count == 0)
            {
                //rkApp.SetValue("SetTimerAlert", Application.ExecutablePath.ToString());
                MessageBox.Show("Please run programs.");
                count++;
            }
            else
            {
                MessageBox.Show("Hey! I did not see the program runs. Your computer will be shut down for 15 seconds.");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

如果您只使用类的静态成员(例如属性,方法等),或者您不使用类的任何成员 - 请将该方法设为静态。
否则它必须是非静态的 private表示无法在课堂外访问,因此如果您不打算在课堂外使用它 - 请将其设为私有
void表示该方法不返回任何内容 因此,在您的情况下SetTimer不会返回任何内容void,因为它不使用任何类成员,它可以是static,如果不是计划在课外使用它,你可以使它private 所以你的方法签名应该是:

public static void SetTimer(int hh, int mm, int ss)  

同样,除非它不是从课外调用,否则它应该是:

private static void setTimer(int hh, int mm, int ss)  

注意:命名约定规定私有方法的名称以非大写字母

开头

由于SetTimer同时使用countProcessTimerEvent,因此您应同时static同时使用{{1}}。

答案 1 :(得分:0)

如果由静态方法“Main”调用,Timer和方法SetTimer也必须是静态的。静态方法不能调用类的实例方法,但实例可以调用静态方法。