在这种情况下如何防止空引用异常

How to prevent null reference exception in this case

 var ans = await client.GetStringAsync(uri);
        JToken[] JSONResponseWeb = new JToken[1];
        JToken[] JSONResponseImage = new JToken[1];

        JSONResponseWeb = JToken.Parse(ans)["webPages"]["value"].ToArray();

        JSONResponseImage = JToken.Parse(ans)["images"]["value"].ToArray();

这里如何防止空引用函数?即...假设我消费的 api 没有 属性 "images"

最短路径(C# 6 及更高版本):

JSONResponseImage = JToken.Parse(ans)?["images"]?["value"]?.ToArray();

其他方式(也低于 C# 6):

JSONResponseImage = null;
var parseResult = JToken.Parse(ans);
if (parseResult != null)
    if (parseResult["images"] != null)
        if (parseResult["images"]["value"] != null)
            JSONResponseImage = parseResult["images"]["value"].ToArray();

或者(风格不好,避免):

var parseResult = JToken.Parse(ans);
JSONResponseImage = parseResult != null
                    ? (parseResult["images"] != null
                       ? (parseResult["images"]["value"] != null
                          ? parseResult["images"]["value"].ToArray()
                          : null)
                       : null)
                    : null;

最糟糕的方式(见评论):

JSONResponseImage = null;
try
{
    JSONResponseImage = JToken.Parse(ans)["images"]["value"].ToArray();
}
var ans = await client.GetStringAsync(uri);
    JToken[] JSONResponseWeb = new JToken[1];
    JToken[] JSONResponseImage = new JToken[1];
    var responseResult = JToken.Parse(ans);
    // Check if you have a null value anywhere in these parameters. This doesn't assume any handling for null values you'll have to figure that out on your end.  Add en else statement and go to town. 
    if (responseResult?["webPages"]?["value"] != null)
    {
        JSONResponseWeb = responseResult ["webPages"]["value"].ToArray();
    }

    if (responseResult?["images"]?["value"] != null)
    {
        JSONResponseWeb = responseResult ["images"]["value"].ToArray();
    }