如何在运行前检测NullReferenceException

本文关键字:检测 NullReferenceException 运行 | 更新日期: 2023-09-27 17:51:23

需要知道是否有任何可用的免费工具或关于如何在运行前检测NullReferenceException ?

比如,我有一段代码像
    SomeObject.SomeMethod() // Here SomeObject can throw NullReferenceException 

有没有办法在运行前检测到这个

如何在运行前检测NullReferenceException

为什么不在调用SomeObject之前检查它是否为空?

c# 6

SomeObject?.SomeMethod();

c# 6之前的

if(SomeObject!=null) SomeObject.SomeMethod();    

你将无法捕获错误因为这是一个运行时错误但是你可以将代码放入try catch中捕获并处理你想要的错误

try {
    SomeObject.SomeMethod() 
}
catch(NullReferenceException) {    
 //catch exception here
}