如果对象为空,是否有创建新对象的快捷方式?

Ala*_*an2 -2 c#

我有一些简单的代码:

    public static void InitializeScreenTimeStopwatch()
    {
        if (ScreenTimeStopwatch == null)
            ScreenTimeStopwatch = new Stopwatch();
    }
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以使用 ? 现在使用最新版本的 C# 的运算符

Dai*_*Dai 5

this.ScreenTimeStopwatch = this.ScreenTimeStopwatch ?? new Stopwatch();
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 C# 8,那么您可以简单地编写以下代码:

this.ScreenTimeStopwatch ??= new Stopwatch();
Run Code Online (Sandbox Code Playgroud)