我有很多支票,但我仍然收到此空错误
I have lots of checks but I am still getting this null error
我同时使用 Unity 和 Visual Studio 来管理一个使用 Unity 和 c# 的网站。
我有一张可以正常加载的世界地图,但在浏览器控制台中显示此错误:
ArgumentNullException: Value cannot be null.
Parameter name: key
所以我加载了 Unity,看看是否能找到任何错误,我看到了一个名为 MapDisplay.cs.
的文件
查看错误,我假设它与字典对象有关。
在那个代码文件中,确实有一个字典对象。
但是,代码似乎正在检查任何可能为空的内容。
所以我不确定我还能检查多少?
是否有更有效的方法来检查字典中的空值以便不显示错误?
这是字典对象的代码:
public Dictionary<string, MapController> MapDictionary;
MapController mapController = CreateMapController(mapData);
if (mapController != null)
{
if (mapController.MapId != null || mapController.MapId != "")
{
string mapControllerId = mapController.MapId;
if (!MapDictionary.ContainsKey(mapControllerId))
{
MapDictionary.Add(mapControllerId, mapController);
}
}
}
谢谢!
除了评论中讨论的 if
条件问题。
您可以使用 (?.
) 可选链接来处理 mapController
可能是 null
。
对于 .NET Core,您可以使用 Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Method。
string mapControllerId = mapController?.MapId;
if (!String.IsNullOrEmpty(mapControllerId))
{
MapDictionary.TryAdd(mapControllerId, mapController);
}
如果没有,可以写一个Dictionary扩展方法TryAdd
来处理
public static class DictionaryExtensions
{
public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue @value)
{
try
{
dict.Add(key, @value);
return true;
}
catch
{
return false;
}
}
}
我同时使用 Unity 和 Visual Studio 来管理一个使用 Unity 和 c# 的网站。
我有一张可以正常加载的世界地图,但在浏览器控制台中显示此错误:
ArgumentNullException: Value cannot be null.
Parameter name: key
所以我加载了 Unity,看看是否能找到任何错误,我看到了一个名为 MapDisplay.cs.
的文件查看错误,我假设它与字典对象有关。
在那个代码文件中,确实有一个字典对象。
但是,代码似乎正在检查任何可能为空的内容。
所以我不确定我还能检查多少?
是否有更有效的方法来检查字典中的空值以便不显示错误?
这是字典对象的代码:
public Dictionary<string, MapController> MapDictionary;
MapController mapController = CreateMapController(mapData);
if (mapController != null)
{
if (mapController.MapId != null || mapController.MapId != "")
{
string mapControllerId = mapController.MapId;
if (!MapDictionary.ContainsKey(mapControllerId))
{
MapDictionary.Add(mapControllerId, mapController);
}
}
}
谢谢!
除了评论中讨论的 if
条件问题。
您可以使用 (?.
) 可选链接来处理 mapController
可能是 null
。
对于 .NET Core,您可以使用 Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Method。
string mapControllerId = mapController?.MapId;
if (!String.IsNullOrEmpty(mapControllerId))
{
MapDictionary.TryAdd(mapControllerId, mapController);
}
如果没有,可以写一个Dictionary扩展方法TryAdd
来处理
public static class DictionaryExtensions
{
public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue @value)
{
try
{
dict.Add(key, @value);
return true;
}
catch
{
return false;
}
}
}