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

时间:2017-04-19 13:13:10

标签: c# nullreferenceexception

 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没有财产"图像"

2 个答案:

答案 0 :(得分:0)

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

private string GetCountry(uint ipNum)
{
    string resultStr= null;
    string query = $@"SELECT Country 
                    FROM tb_CountryIP 
                    WHERE {ipNum} >= IP_From 
                      AND {ipNum} <= IP_To";

    try
    {
        using(SqlConnection sqlConn = new SqlConnection(ConnectionStr)) 
        using(SqlCommand sqlComm = new SqlCommand(query, sqlConn))
        {
            sqlConn.Open();
            object result = sqlComm.ExecuteScalar();
            if(result != null)
                resultStr = result.ToString();
        }
    }
    catch(Exception ex)
    {
        resultStr= $"Error : {ex.Message}";
    }
    return resultStr;
}

其他方式(也在C#6下面):

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

或(不好的风格,避免它):

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;

答案 1 :(得分:0)

JSONResponseImage = null;
try
{
    JSONResponseImage = JToken.Parse(ans)["images"]["value"].ToArray();
}