简体   繁体   中英

Can't find why do I have a null reference exception

Below is the code and the problematic line.

When I hover with the mouse on src.EnergyServiceLevel , it shows that it's null. How can that be if I'm checking for null in the previous line?

My guess was that maybe there are threads that making the problem so I've add a lock, but it didn't helped.

public static ServiceLevelsGroup SafeClone(this ServiceLevelsGroup src) {
  ServiceLevelsGroup res = null;
  lock (_locker) {
    if (src != null) {
      res = new ServiceLevelsGroup();
      if (src.EnergyServiceLevel != null) {
        res.EnergyServiceLevel = new ServiceLevelInfo { ServiceGrade = src.EnergyServiceLevel.ServiceGrade };

        if (src.EnergyServiceLevel.Reason != null)
          res.EnergyServiceLevel.Reason = src.EnergyServiceLevel.Reason;
      }
    }
  }

  return res;
}

The exception occurs at the res.EnergyServiceLevel = ... line in the above code.

Here's a screenshot of the exception occurring in debug mode:

调试时异常的屏幕截图

Your code shows lock(_locker) - so it looks like you're in a multithreaded environment. Can you check that nothing else is NULLing your variable? ie that everything else is also calling lock(_locker) correctly?

也许您的NULL位于res.EnergyServiceLevel

src.EnergyServiceLevel.ServiceGrade may be null

Moving mouse pointer to each reference will exactly show you which is null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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