所以这就是问题的关键:Foo.Bar可以返回null吗?为了澄清,'_bar'在被评估为非null并且在返回值之前可以设置为null吗?
public class Foo
{
Object _bar;
public Object Bar
{
get { return _bar ?? new Object(); }
set { _bar = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
我知道使用以下get方法不安全,并且可以返回null值:
get { return _bar != null ? _bar : new Object(); }
Run Code Online (Sandbox Code Playgroud)
更新:
另一种看待同一问题的方法,这个例子可能更清楚:
public static T GetValue<T>(ref T value) where T : class, new()
{
return value ?? new T();
}
Run Code Online (Sandbox Code Playgroud)
并再次询问GetValue(...)是否会返回null?根据你的定义,这可能是也可能不是线程安全的...我猜正确的问题陈述是询问它是否是一个关于价值的原子操作...... David Yaw已经通过说上面的函数等效来定义问题了以下内容:
public static T GetValue<T>(ref T value) where T : class, new()
{
T result = value;
if …Run Code Online (Sandbox Code Playgroud) 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(); …Run Code Online (Sandbox Code Playgroud)