找不到为什么会出现空引用异常
下面是代码和有问题的行。
当我将鼠标悬停在 src.EnergyServiceLevel 上时,它显示它为空。 如果我在前一行中检查 null ,那怎么可能呢?
我的猜测是,也许有线程造成了问题,所以我添加了一个锁, 但这没有帮助。
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;
}
异常发生在上述代码中的 res.EnergyServiceLevel = ...
行。
这是调试模式下发生的异常的屏幕截图:
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:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码显示
lock(_locker)
- 所以看起来您处于多线程环境中。你能检查一下没有其他东西使你的变量为空吗?即其他所有内容也都正确调用lock(_locker)
吗?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? i.e. that everything else is also callinglock(_locker)
correctly?也许您的 NULL 位于
res.EnergyServiceLevel
。Maybe your NULL is at
res.EnergyServiceLevel
.src.EnergyServiceLevel.ServiceGrade
可能为空 将鼠标指针移动到每个引用将准确显示哪个为空。
src.EnergyServiceLevel.ServiceGrade
may be nullMoving mouse pointer to each reference will exactly show you which is null.