【问题标题】:Perform lots of checks but still get error when inserting data into Dictionary执行大量检查,但在将数据插入字典时仍然出错
【发布时间】:2022-10-08 09:58:13
【问题描述】:

我同时使用 Unity 和 Visual Studio 来管理使用 Unity 和 C# 的网站。

我有一个加载正常的世界地图,但在浏览器控制台中显示此错误:

ArgumentNullException:值不能为空。

参数名称:key

所以我加载了 Unity,看看我是否能找到任何错误,并看到一个名为的文件地图显示.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);
        }
    }
}

谢谢!

【问题讨论】:

  • 使用!String.IsNullOrEmpty(mapController.MapId)mapController.MapId != null || mapController.MapId != "" 的值为 null,if 条件为真。
  • 这个条件if (mapController.MapId != null || mapController.MapId != "") 将始终评估为true,我认为这不是你想要的。
  • 你想要 && (AND) NOT || (或者)。 string.IsNullOrWhiteSpace(mapController.MapId) 方法已经可以做到这一点。
  • 提高@Ralf .. 请注意,IsNullOrWhiteSpace 涵盖了更多的边缘情况,例如只有空格和制表符.. 在这种情况下这不太重要,但它与检查null"" 不完全相同;).. 在这个用例中,它很可能是你想要的,因为如前所述..它涵盖了更多的边缘情况
  • @derHugo 正确。您可能错过了提到string.IsNullOrEmpty 作为他检查的确切对应方法;)

标签: c# dictionary unity3d


【解决方案1】:

除了 cmets 中讨论的if 条件问题。

您可以使用 (?.) 可选链接来处理 mapController 可能是 null

使用 .NET Core,您可以使用 Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Method

string mapControllerId = mapController?.MapId;

if (!String.IsNullOrEmpty(mapControllerId))
{
    MapDictionary.TryAdd(mapControllerId, mapController);
}

如果没有,可以为TryAdd写一个Dictionary扩展方法来处理。

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;
        }
    }
}

【讨论】:

  • 谢谢,您编写的代码string mapControllerId = mapController?.MapId ?? ""; 是否意味着如果 mapController 或 mapController.MapId 为空或 null,那么 mapControllerId 将是一个类似 "" 的字符串?
  • 其实mapController?. MapId 就够了,不需要nullish 运算符。作为下一个 if 语句将检查 null 或空字符串。可选链接旨在安全访问嵌套属性。当发现该值为 null 时,它将不会继续访问嵌套属性。
猜你喜欢
  • 2016-05-30
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多