C# 构造函数和常量之谜

标签 c# constructor class-constants

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

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

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

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

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

最佳答案

想法:

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

进一步的想法:

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

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

关于C# 构造函数和常量之谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9776347/

相关文章:

java - 如何创建对象的实例而不在构造函数中传递参数?

javascript - 给定一个函数 A,new A() 和 new A 之间有什么区别吗?

ruby - 如何在 Ruby 中创建私有(private)类常量

compiler-errors - Eiffel : once function has generic or anchored result. Trying to create constants

c# - MahApps MetroProgressBar 无法在 ControlTemplate 内工作

c# - 这是一个错误吗?具有私有(private)访问修饰符构造函数的 Activator.CreateInstance?

c# - Nuget 版本控制 : Wildcard vs unspecified component

python - 如何避免使用 Python 继承重新定义默认参数

php - 在php中获取类常量名称?

c# - 枚举是否会变得过于臃肿?