【问题标题】:Can you shorten multiple chained null checks in C#? [duplicate]你能在 C# 中缩短多个链式空检查吗? [复制]
【发布时间】:2020-08-09 15:46:29
【问题描述】:

我刚刚开始学习 C#。我正在为 Rimworld 制作游戏模组,无法修改典当代码。显然,任何链接的对象都可能为空。有没有比我做的更好的方法来摆脱这种方法?

谢谢。

    private void cleanseParadoxicalMemories(Pawn pawn, Dictionary<string, string> knownPawnIDs)
    {
        if (pawn.needs == null || pawn.needs.mood == null || pawn.needs.mood.thoughts == null || pawn.needs.mood.thoughts.memories == null)
        {
            return;
        }

        // Remove any crazy-making memories from a now-invalid timeline due to traveling across an Einstein-Rosen bridge
        // (basically, selective amnesia about everyone not going with us.)
        foreach (var paradox in pawn.needs.mood.thoughts.memories.Memories.ToList())
        {
            if (paradox.otherPawn != null)
            {
                pawn.needs.mood.thoughts.memories.RemoveMemory(paradox);
            }
        }
    }

【问题讨论】:

  • 我认为你可以在这里使用?.,至少在 if 中。如果其中任何一个是,pawn.needs?.mood?.thoughts?.memories 将为空。如果我没记错的话foreach 不喜欢空值,所以不能把整个东西放在里面
  • foreach(var paradox in (pawn?.needs?.mood?.thoughts?.memories?.Memories ?? Enumerable.Empty&lt;ParadoxType&gt;()).ToList())

标签: c#


【解决方案1】:

您可以使用空条件运算符?. 来实现:

private void cleanseParadoxicalMemories(Pawn pawn, Dictionary<string, string> knownPawnIDs)
{
   if (pawn?.needs?.mood?.thoughts?.memories == null)
   {
      return;
   }

   // Remove any crazy-making memories from a now-invalid timeline due to traveling across an Einstein-Rosen bridge
   // (basically, selective amnesia about everyone not going with us.)
   foreach (var paradox in pawn.needs.mood.thoughts.memories.Memories.ToList())
   {
      if (paradox.otherPawn != null)
      {
         pawn.needs.mood.thoughts.memories.RemoveMemory(paradox);
      }
   }

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 2020-12-30
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2011-09-28
    • 1970-01-01
    相关资源
    最近更新 更多