C#检查引用是否为null - 运行时绑定错误

时间:2018-03-17 13:00:03

标签: c# if-statement nullreferenceexception

我收到此错误:

Cannot perform runtime binding on a null reference

当我尝试将一个JSON对象分配给var

var vrlvl = dataFirst.payload.last_quick_matches.csgo.skill_level;

如何在分配对象之前检查对象是否为空?

我已尝试过这些,但它会出现同样的错误

if (dataFirst.payload.last_quick_matches.csgo.skill_level != null)

if (Object.ReferenceEquals(null, dataFirst.payload.last_quick_matches.csgo.skill_level)) 

1 个答案:

答案 0 :(得分:0)

您可能还需要检查几个级别:

if (dataFirst && dataFirst.payload && dataFirst.payload.last_quick_matches && dataFirst.payload.last_quick_matches.csgo && dataFirst.payload.last_quick_matches.csgo.skill_level)
{
    var vrlvl = dataFirst.payload.last_quick_matches.csgo.skill_level;
}

编辑:试试这个:

if (dataFirst != null && dataFirst.payload != null && dataFirst.payload.last_quick_matches != null && dataFirst.payload.last_quick_matches.csgo != null && dataFirst.payload.last_quick_matches.csgo.skill_level != null)
{
    var vrlvl = dataFirst.payload.last_quick_matches.csgo.skill_level;
}