我想知道为什么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不会抱怨第一个版本。当然,我确实缺少有关这段代码的本质的东西。
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 evaluatedate
, and it won't callToString()
on anything - so you won't get an exception.完整的例子:
Here the expression
t?.date.ToString()
is equivalent to:(except that
t
is only evaluated once). It's not equivalent to...这就是我怀疑您期望它执行的操作。