当我运行此代码时,我得到了一个意外NullReferenceException
,省略了fileSystemHelper
参数(因此将其默认为 null):
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
,仍然有 null 值,如此屏幕截图所示(跨过下一行 throws NullReferenceException
):
这不是我所期望的!我期望 null 合并运算符发现参数为 null 并创建一个new FileSystemHelper()
. 我已经盯着这段代码很久了,看不出它有什么问题。
ReSharper 指出该字段仅用于这一种方法,因此可能会转换为局部变量……所以我尝试了一下,你猜怎么着?有效。所以,我有我的解决方案,但我无法终生明白为什么上面的代码不起作用。我觉得我正在学习一些关于 C# 的有趣的东西,或者我做了一些非常愚蠢的事情。谁能看到这里发生了什么?