2

为什么静态构造函数在引用另一个类中的 const 字符串时会抛出异常。

 class MyClass
 {  
      static MyClass() 
      { 
           ExamineLog();   
      }

      static ExamineLog()  
      {
          FilePath = HttpContext.Current.Server.MapPath(Helper.LogConfiguration);                
      }
}

class Helper
{  
      public const string LogConfiguration= "\rootpath\counters.txt";
}

抛出的异常是对象引用未设置为对象的实例。堆栈跟踪指向尝试读取常量值的行。有什么想法吗?

4

3 回答 3

6

想法:

  • HttpContext可能为空
  • HttpContext.Current可能为空
  • HttpContext.Current.Server可能为空

进一步的想法:

CurrentHttpContext类的静态属性,所以HttpContext不是对象引用,不能为空。如果您想简化调试,可以像这样更改代码(我假设ExamineLog应该将其声明为 void 方法):

static void ExamineLog()   
{
    var context = HttpContext.Current;
    var server = context.Server;
    FilePath = server.MapPath(Helper.LogConfiguration);                 
} 
于 2012-03-19T19:11:51.577 回答
0

我的第一个赌注是一个坏字符串......

"\rootpath\counters.txt" // => "\r" is carriage return

所以 MapPath 失败了。

于 2012-03-19T19:13:15.083 回答
0

我的猜测是 HttpContext.Current 在静态构造函数的上下文中为空。自从我深入 ASP.NET 以来已经有一段时间了,但是 IIRC,除非您处于页面的请求-响应生命周期中,否则不会设置 HttpContext.Current。我不知道什么时候必须在 ASP.NET 应用程序中执行静态构造函数(从技术上讲,应该是在第一次被代码访问时),在您的情况下,它很容易处于此页面生命周期之外的上下文中。

我怀疑 null 引用来自您的 const 引用:const 引用在编译时作为文字值/字符串插入,因此不应该抛出运行时 null 引用异常。

于 2012-03-19T19:23:44.730 回答