当我尝试使用一种方法在我的日志文件上写入时,我遇到了一个问题,即我声明的 StreamWriter 被处置。一切都按预期工作,除非我从另一个班级运行AttachPink或AttachBlue。然后处理 StreamWriter,我得到一个 nullPointerException
class Logs : IDisposable
{
//other declarations
private StreamWriter HistoryWriter;
private int ReportInterval = 0;
public void NewHistory()
{
HistoryWriter = new StreamWriter(HistoryLocation + HistoryName + HistoryExtension);
PrepareHistory();
}
private void PrepareHistory()
{
HistoryWriter.WriteLine("<html><body bgcolor='#000000'>");
/*
* Insert initial HTML tags
*/
}
public void SendHistory()
{
HistoryWriter.WriteLine("</body></html>");
/*
* Final HTML tags
*/
HistoryWriter.Close();
if (ReportInterval > 0)
{
/*
* Upload File
*/
}
else
{
Debug.WriteLine("ERROR: Report Interval for History has not been set");
}
NewHistory();
}
public void AttachPink(String message, StreamWriter writer)
{
writer.Write(
"<font color='DA1BE0'>"
+ message
+ "</font>");
}
public void AttachBlue(String message, StreamWriter writer)
{
writer.Write(
"<font color='0C93ED'>"
+ message
+ "</font>");
}
public StreamWriter getHistoryWriter()
{
return HistoryWriter;
}
public void SetHistoryInterval(int interval)
{
ReportInterval = interval;
}
public void Dispose()
{
if (HistoryWriter != null)
{
HistoryWriter.Close();
HistoryWriter.Dispose();
HistoryWriter = null;
}
}
}
要使用这些方法,我只需在另一个类中声明 Logs 类的实例,如下所示:
class UsingLogs
{
Logs logs = new Logs();
logs.NewHistory();
logs.AttachBlue("my message", logs.getHistoryWriter());
}
我不知道在访问多个方法时应该如何保留类变量状态。