0

我想创建一个通用的记录器类。这抱怨“值不能为空。参数名称:路径”。初始化对象后,我得到 logname 值但没有 log。我哪里做错了?

class Logger
{

    public static string log;


    public Logger(string logname)
    {
        log = logname;

    }
    StreamWriter writer = new StreamWriter(log);
}
4

1 回答 1

10

试试这个:

...
    public Logger(string logname)
    {
         log = logname;
         writer = new StreamWriter(log);
    }
    StreamWriter writer = null;
...

您有此错误,因为 first 执行以下行:

StreamWriter writer = new StreamWriter(log);

在那一刻,字段日志为空,因为构造函数是在字段初始化之后执行的。

于 2013-01-08T23:37:39.797 回答