为什么Visual Studio不会警告我有关null引用异常的信息?

我想知道为什么Visual Studio 2019不会抱怨这段C#代码:

dynamic deserializedBody = JsonConvert.DeserializeObject(requestBody);
deserializedBody?.date.ToString();

Since deserializedBody?.date could be null, it would mean that the ToString method would be applied to something null. I think something like this:

deserializedBody?.date?.ToString();

会是正确的使用形式,但Visual Studio不会抱怨第一个版本。当然,我确实缺少有关这段代码的本质的东西。

评论
Lamb
Lamb

The null-safe dereferencing operator stops evaluation of the whole expression as soon as it hits null. So if deserializedBody is null, it won't try to evaluate date, and it won't call ToString() on anything - so you won't get an exception.

完整的例子:

using System;

class Test
{
    DateTime date = DateTime.UtcNow;

    static void Main()
    {
        Test t = null;
        // No exception thrown
        Console.WriteLine(t?.date.ToString());
    }    
}

Here the expression t?.date.ToString() is equivalent to:

t is null ? null : t.date.ToString()

(except that t is only evaluated once). It's not equivalent to

(t is null ? null : t.date).ToString()

...这就是我怀疑您期望它执行的操作。

点赞
评论