当我清楚地调用这个单例并且它应该调用Logger()来设置filename变量时,我无法弄清楚为什么我继续在文件名上获得空引用:
public class Logger
{
private static Logger defaultLogger = null;
readonly string filename;
public static Logger DefaultLogger
{
get
{
// Check for valid instance
if (defaultLogger == null)
defaultLogger = new Logger();
// Return instance
return defaultLogger;
}
}
private Logger()
{
filename = ConfigurationManager.AppSettings["MyLogPath"];
}
public string Filename
{
get { return this.filename; }
}
public void Write(EntryType type, string data)
{
lock (this)
{
using (StreamWriter writer = new StreamWriter(filename, true))
{
//do something
}
}
}
}
以下是我如何称呼这个课程:
Logger.DefaultLogger.Write(EntryType.Error, e.ToString());
所以我在运行时遇到这个错误,说文件名为null:
Value cannot be null.
Parameter name: path
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: path
Source Error:
Line 49:
Line 50:
Line 51: public string Filename
Line 52: {
Line 53: get { return this.filename; }
这是我们的原始代码(我没有写这个),同样的问题:
public class Logger
{
public static Logger DefaultLogger = new Logger();
string filename;
public Logger()
{
filename = ConfigurationManager.AppSettings["LogPath"];
}
public Logger(string filename)
{
this.filename = filename;
}
public string Filename
{
get { return this.filename; }
}
public void Write(LogEntryType type, string data)
{
lock ()
{
using (StreamWriter writer = new StreamWriter(filename, true))
{
...
}
}
}
答案 0 :(得分:6)
是因为
ConfigurationManager.AppSettings["MyLogPath"];
是空的吗?
检查您的App.Config
文件是否存在(在bin文件夹中采用yourexe.exe.config
的形式)。你App.Config应该有以下几行:
<configuration>
<appSettings>
<add key="MyLogPath" value="C:\Simple.txt" />
<appSettings>
</configuration>
也许为了测试,您可以临时将文件名设置为知道路径(filename=@"D:\C#\mytext.txt";
)并查看是否收到错误。
如果我明确设置文件名,那么如果我设置
,我就不会有这样的错误OTOHfilename=ConfigurationManager.AppSettings["MyLogPath"];
然后我会得到一个
System.ArgumentNullException:Value 不能为空。参数名称:路径 在 System.IO.StreamWriter..ctor(字符串 path,布尔附加,编码 编码,Int32 bufferSize)at System.IO.StreamWriter..ctor(字符串 path,Boolean append)
如果我使用调试器,我可以看到它失败了:
(StreamWriter writer = new StreamWriter(filename, true))
我不知道为什么你的调试器不会命中构造函数。在这两种情况下,我的调试器都会点击构造函数。
答案 1 :(得分:1)
没有太多考虑..
private Logger()
{
filename = ConfigurationManager.AppSettings["MyLogPath"];
throw new Exception("filename = "+filename);
}
是否抛出异常?
答案 2 :(得分:1)
我复制粘贴代码并替换
filename = ConfigurationManager.AppSettings["MyLogPath"];
与
filename = @"test.log";
它工作正常。因此,您的错误是拼写"MyLogPath"
或app.config
。
答案 3 :(得分:0)
静态初始化器在首次访问类定义时执行,在您的情况下意味着它们在私有构造函数之前执行。
答案 4 :(得分:0)
您正在使用锁,因此您希望在多线程方案中调用此方法,但不要同步DefaultLogger。另外,您确定首先将fileName设置为非null值吗?
答案 5 :(得分:0)
尝试将Logger分配给客户端代码中的实例变量并访问它的FileName。也许它没有被正确分配 此外,如果您只提供获取属性,是否需要将文件名设置为只读?