[英]How to call another function in the “static main” method?
我是C#的初學者,我想在static void Main()
調用一個名為SetTimer()
的函數,但它給出了一些錯誤,如SetTimer(11, 48, 00);
和SetTimer(11, 35, 40);
下面。 實際上,通過Main()
函數,它可能在Form反之亦然。 我對如何以及何時使用這些類型感到困惑:
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.");
}
}
}
}
如果您僅使用類的靜態成員(例如屬性,方法等),或者不使用類的任何成員,則將方法設為靜態。
否則它必須是非靜態的。
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
使用count
和ProcessTimerEvent
,因此您也應該使它們均為static
。
如果由靜態方法“ Main”調用,則Timer和SetTimer方法也必須均為靜態。 該類的實例方法不能由靜態方法調用,但是實例可以調用靜態方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.