我有一個使用 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
如您所見,我正在嘗試使用 null 檢查。
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的方法嗎?
謝謝!
uj5u.com熱心網友回復:
如果Weathertypes
為null,以下代碼將導致空參考例外:
if (WeatherTypes[i].WeatherId != null || WeatherTypes[i].WeatherId != "")
更安全的方法如下所示。
if (WeatherTypes == null || WeatherTypes[i] == null)
您應該學習使用除錯器。它將允許您單步執行代碼并查看究竟什么是空的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461613.html
下一篇:返回列表