0

当我尝试使用一种方法在我的日志文件上写入时,我遇到了一个问题,即我声明的 StreamWriter 被处置。一切都按预期工作,除非我从另一个班级运行AttachPinkAttachBlue。然后处理 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());
    }

我不知道在访问多个方法时应该如何保留类变量状态。

4

1 回答 1

2

我猜你正在寻找的是单例模式(http://en.wikipedia.org/wiki/Singleton_pattern

我的一个简单实现,每次需要单例时都可以重用

public class Singleton<T> where T : class, new()
{
    private static object sync = null;
    private static volatile T i;
    protected Singleton() { }

    public static T I
    {
        get
        {
            if (i == null)
                lock (sync)
                    if (i == null)
                        i = new T();

            return i;
        }
    }
}

您可以像这样实现您的 Log 类:

class Logs : Singleton<Logs>
{
... your code goes here
}

在您的代码中,当您想使用 Logs 类时,您只需使用:

Logs.I.AttachBlue(...);

希望这可以帮助 :)

于 2013-01-20T21:06:28.633 回答