当我运行这段代码并省略fileSystemHelper
参数(因此默认为null)时,出现了意外的NullReferenceException
异常:
public class GitLog
{
FileSystemHelper fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="GitLog" /> class.
/// </summary>
/// <param name="pathToWorkingCopy">The path to a Git working copy.</param>
/// <param name="fileSystemHelper">A helper class that provides file system services (optional).</param>
/// <exception cref="ArgumentException">Thrown if the path is invalid.</exception>
/// <exception cref="InvalidOperationException">Thrown if there is no Git repository at the specified path.</exception>
public GitLog(string pathToWorkingCopy, FileSystemHelper fileSystemHelper = null)
{
this.fileSystem = fileSystemHelper ?? new FileSystemHelper();
string fullPath = fileSystem.GetFullPath(pathToWorkingCopy); // ArgumentException if path invalid.
if (!fileSystem.DirectoryExists(fullPath))
throw new ArgumentException("The specified working copy directory does not exist.");
GitWorkingCopyPath = pathToWorkingCopy;
string git = fileSystem.PathCombine(fullPath, ".git");
if (!fileSystem.DirectoryExists(git))
{
throw new InvalidOperationException(
"There does not appear to be a Git repository at the specified location.");
}
}
当我在调试器中单步执行代码时,在跨过第一行(带 ??
运算符的行)后, fileSystem
仍然具有空值,如此屏幕截图所示(跨过下一行会抛出 NullReferenceException
):
![When is null not null?](https://istack.dev59.com/HkDtr.webp)
new FileSystemHelper()
。我已经盯着这段代码看了很长时间,但还是看不出问题出在哪里。ReSharper指出该字段仅在此方法中使用,因此可能可以转换为局部变量……因此我尝试了一下,猜猜怎么着?它奏效了。所以,我已经解决了问题,但我却无法看出为什么上面的代码不起作用。我感觉我快要学习到一些有趣的关于C#的东西,或者我做了什么愚蠢的事情。有人能看出这里发生了什么吗?
fileSystemHelper
为null
,我不确定,但可能与此有关。但再说一遍,这只是我的猜测。 - trinaldi