我有以下方法,Resharper告诉我,这if(drivers != null)将永远是真的,但我不知道为什么,它告诉我catch块是多余的,但有人可以解释为什么?这是代码:
public List<Driver> GetDrivers(int id)
{
if (_context != null)
{
try
{
var drivers = _context.Drivers.Where(x=> x.id == id).ToList();
//Always true
if (drivers != null)
{
//code
}
else
{
//Heuristically unreachable
throw new Exception("No Driver");
}
}
catch (Exception ex)
{
throw;
}
}
return drivers;
}
Run Code Online (Sandbox Code Playgroud)
if(drivers != null)总是如此?驱动程序不能为空吗?如果它是正确的,我假设有一个非空的驱动程序的默认值.catch是多余的,但除了是null之外,哪个resharper说它不能,是不是还有另一个可能导致catch执行的异常?好吧,捕获确实是多余的,你没有做任何事情,只是重新抛出完全相同的异常:
catch (Exception ex)
{
// would make more sense if for example you're writing to log file
// otherwise this will be thrown anyway (even without the catch)
throw;
}
Run Code Online (Sandbox Code Playgroud)
此外,这永远不会返回null,它可能有0个条目,但它不会为null:
_context.Drivers.Where(x=> x.id == id).ToList();
Run Code Online (Sandbox Code Playgroud)