访问方法时处理StreamWriter

时间:2013-01-20 20:46:10

标签: c# .net class

当我尝试使用方法在我的日志文件上写入时,我遇到了我声明的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());
    }

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

1 个答案:

答案 0 :(得分:2)

我猜你要找的是Singleton模式(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(...);

希望这会有所帮助:)