Когда я пытаюсь скомпилировать приведенный ниже код, я получаю одну ошибку:
Ссылка на объект требуется для нестатического поля, метода или свойства «Program._timer».
Я понял от кого-то еще в этой теме, что не могу создать такую переменную в моем статическом Main(), но я не уверен, как мне ее изменить, чтобы получить функциональность, которую я пытаюсь достичь.
Я попытался использовать этот код для создания таймера, но именно так я застрял в этой ошибке. Как добавить таймер в консольное приложение C#
using System;
using System.Xml.Linq;
using Microsoft.Win32;
using static Microsoft.Win32.SystemEvents;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Diagnostics.Metrics;
using System.Timers;
using System.Threading;
namespace CSharpTutorials
{
class Program
{
private System.Threading.Timer _timer = null;
public static void Main()
{
DateTime lastLogin, lastLock;
string bossEmail;
XDocument doc = XDocument.Load("properties.xml");
XElement lastLockElement = doc.Descendants("lastLock").FirstOrDefault();
//lastLockElement.FirstAttribute.Value
XElement lastLoginElement = doc.Descendants("lastLogin").FirstOrDefault();
//lastLoginElement.FirstAttribute.Value
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
var mre = new ManualResetEvent(false);
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
{
mre.Set();
};
mre.WaitOne();
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
_timer = new System.Threading.Timer(TimerCallback, null, 0, 2000);
}
private static void TimerCallback(Object o)
{
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + DateTime.Now);
}
public static string GetTimestamp(DateTime value)
{
return value.ToString("yyyy/MM/dd HH:mm:ss");
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
string timeStamp = GetTimestamp(DateTime.Now);
// Load the XML file
XDocument doc = XDocument.Load("prefrences.xml");
switch (e.Reason)
{
case SessionSwitchReason.SessionLogon:
//Logon
//RecordLog(timeStamp + ": User logged into the session.");
XElement logonElement = doc.Descendants("lastLogin").FirstOrDefault();
if (logonElement != null)
{
// Modify the element's attributes or values with variables
logonElement.SetAttributeValue("lastLogin", DateTime.Now);
doc.Save("properties.xml");
}
break;
case SessionSwitchReason.SessionLogoff:
//Logoff
//RecordLog(timeStamp + ": User logged off the session.");
break;
case SessionSwitchReason.RemoteConnect:
//Remote Connect
//RecordLog(timeStamp + ": User remote connected.");
break;
case SessionSwitchReason.RemoteDisconnect:
//Remote Disconnect
//RecordLog(timeStamp + ": User remote disconnected.");
break;
case SessionSwitchReason.SessionLock:
//lockQ
//RecordLog(timeStamp + ": User locked the computer.");
// Find the element you want to modify
XElement lockElement = doc.Descendants("lastLock").FirstOrDefault();
if (lockElement != null)
{
// Modify the element's attributes or values with variables
lockElement.SetAttributeValue("lastLock", DateTime.Now);
doc.Save("properties.xml");
}
break;
case SessionSwitchReason.SessionUnlock:
//Unlock
//RecordLog(timeStamp + ": User unlocked the computer.");
break;
default:
break;
}
}
//private static void RecordLog(string message)
//{
// Add code to record the event in a log file or database
// For example, you can write the message to a log file:
//using (StreamWriter writer = File.AppendText("log.txt"))
//{
//writer.WriteLine(message);
//}
//}
}
}
Извините, если ошибки не так очевидны для меня, как для вас. Я ценю ваше разъяснение. Я не знаю, откуда взялся ProgramHelper.cs, но я от него избавлюсь. Большое спасибо!
Можете ли вы помочь мне с кодом, необходимым для исправления _Timer? Я обновил вопрос, чтобы уточнить.
Поскольку весь ваш код содержится только в методах static
, проще всего было бы сделать _timer
статическим. То есть private static System.Threading.Timer _timer = null
...
Вот ваш ответ - An **object reference** is required for the **non-static field**, method, or property
Чтобы получить доступ к полю экземпляра, инициализируйте новый экземпляр класса Program:
var p = new Program();
p._timer = new System.Threading.Timer(TimerCallback, null, 0, 2000);
или сделать поле статическим:
private static System.Threading.Timer _timer;
public static void Main()
{
...
_timer = new System.Threading.Timer(TimerCallback, null, 0, 2000);
...
}
Ошибки довольно четкие. Читай их. Например, вы пытаетесь использовать нестатическое поле
_timer
в статическом методеMain
. Вы не можете этого сделать. Вы пытаетесь использоватьSystemEvents_SessionSwitch
в другом файле с именемProgramHelpers.cs
. Бьюсь об заклад, этот файл также содержитstatic void Main