[英]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. 当我将鼠标悬停在src.EnergyServiceLevel
,它显示它为null。 How can that be if I'm checking for null in the previous line? 如果我在前一行中检查null,那该怎么办?
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. 异常发生在上面代码中的res.EnergyServiceLevel = ...
行。
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. 您的代码显示lock(_locker)
- 所以看起来您处于多线程环境中。 Can you check that nothing else is NULLing your variable? 你可以检查没有其他东西是你的变量吗? ie that everything else is also calling lock(_locker)
correctly? 即其他一切也正确地调用lock(_locker)
?
也许您的NULL位于res.EnergyServiceLevel
。
src.EnergyServiceLevel.ServiceGrade
may be null src.EnergyServiceLevel.ServiceGrade
可以为null
Moving mouse pointer to each reference will exactly show you which is null. 将鼠标指针移动到每个引用将准确显示哪个为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.