从静态例程 c# 访问方法
本文关键字:访问 方法 例程 静态 | 更新日期: 2023-09-27 18:36:47
我有一个方法
private string sLogFormat;
private string sErrorTime;
public void CreateLogFile(string path, string msg)
{
//sLogFormat used to create log files format :
// dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
//this variable used to create log filename format "
//for example filename : ErrorLogYYYYMMDD
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString();
string sDay = DateTime.Now.Day.ToString();
sErrorTime = sYear + sMonth + sDay;
StreamWriter sw = new StreamWriter(path + sErrorTime, true);
sw.WriteLine(sLogFormat + msg);
sw.Flush();
sw.Close();
}
另一个方法 run() 在某个地方触发 Onchanged 处理程序(当文件夹内容更精确地更改时触发)这里
public static void Run()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:/model_RCCMREC";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// watch wav files.
watcher.Filter = "*.wav";
// Add event handlers.
watcher.Created += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
和 OnChanged 处理程序作为
public static void OnChanged(object source, FileSystemEventArgs e)
{
try
{
//access last folder(newly created one is suposedly at last position)
var directory = new DirectoryInfo("C:/model_RCCMREC");
var myFile = (from f in directory.GetFiles() orderby f.LastWriteTime descending select f).First();
//2.Split the file name.
}
catch
{
//I WANT TO ACCESS THE METHOD CreateLogFile(x,y) HERE
}
}
我无法正常从OnChanged的处理程序访问方法CreateLogFile()。我怎样才能访问它?
似乎OnChanged应该是非静态的。通常只有特定的实例会调用 OnChanged。这是因为某物变化的诺拉格被包裹在它本身的实例中。从您的OnChanged中删除静态,您就可以开始了。
或者,如果您不能/不想使您的OnChanged成为非静态的,则可以将CreateLogFile设置为静态的,我认为没有任何理由在您的方法之外减少变量:
public static void CreateLogFile(string path, string msg)
{
string sLogFormat;
string sErrorTime;
//sLogFormat used to create log files format :
// dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
//this variable used to create log filename format "
//for example filename : ErrorLogYYYYMMDD
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString();
string sDay = DateTime.Now.Day.ToString();
sErrorTime = sYear + sMonth + sDay;
StreamWriter sw = new StreamWriter(path + sErrorTime, true);
sw.WriteLine(sLogFormat + msg);
sw.Flush();
sw.Close();
}
你有两种方法:
1-如果您的记录器类是非静态的,请使用您的记录器类日志 = 新的您的记录器类();并做空洞
2-使您的记录器类静态,使您可以在任何地方轻松使用它:
private static string sLogFormat;
private static string sErrorTime;
public static void CreateLogFile(string path, string msg)
{
...