简体   繁体   English

静态类中的NullReferenceException

[英]NullReferenceException in static class

I have an asp.net application with a static "global" class. 我有一个带有静态“全局”类的asp.net应用程序。 Inside of the static class I have a variable called user. 在静态类内部,我有一个名为user的变量。 When a user logs in a set that variable. 当用户登录设置该变量时。 Debugging through the log process. 通过日志过程进行调试。 All my other static variable seems to be fine except two. 除了两个以外,我所有其他静态变量似乎都不错。 I am not sure why I am getting 'GlobalVariables.User' threw an exception of type 'System.NullReferenceException'. 我不确定为什么要获取“ GlobalVariables.User”引发了“ System.NullReferenceException”类型的异常。 Can anyone shed some light on this. 任何人都可以阐明这一点。 Thanks 谢谢

namespace GlobalClass

public static class GlobalVariables


public static User User { get; set; }

Its probably throwing because you didn't create an instance of User. 可能是因为未创建User实例而引发的。 One way to fix it is the following. 解决该问题的一种方法如下。

public static class GlobalVariables
{
   static GlobalVariables()
   {
       User = new User();
   }

   public static User User { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM