我似乎无法在此 c# Unity 脚本中测试 null

I can't seem to test for a null in this c# Unity script

我有一个使用 c# 的 Unity 应用程序。

我收到一个 NullReferenceException: Object reference not set to an instance of an object 在线:

WeatherDict.Add(WeatherTypes[i].WeatherId, new List<WeatherMaps>());

对于WeatherTypes[i].WeatherId

如您所见,我正在尝试使用 string.IsNullOrWhiteSpace 检查空值。

for (int i = 0; i < WeatherTypes.Length; i++)
{
    if (!string.IsNullOrWhiteSpace(WeatherTypes[i].WeatherId))
    {
        if (!WeatherDict.ContainsKey(WeatherTypes[i].WeatherId))
        {
            WeatherDict.Add(WeatherTypes[i].WeatherId, new List<WeatherMaps>());
        }
    }
}

我也试过这个:

if (WeatherTypes[i].WeatherId != null || WeatherTypes[i].WeatherId != "")

但这仍然会引发相同的异常。

是否有另一种检查 null 的方法?

谢谢!

如果Weathertypes为空,下面的代码会引发空引用异常:

if (WeatherTypes[i].WeatherId != null || WeatherTypes[i].WeatherId != "")

更安全的方法如下所示。

if (WeatherTypes == null || WeatherTypes[i] == null)

你应该学会使用调试器。它将允许您单步执行代码并准确查看空值。