在 C# 中标识空对象

本文关键字:对象 标识 | 更新日期: 2023-09-27 18:31:31

我正在做一个方法调用,它将另外四个方法调用的结果作为参数 - 但是进行这些调用的方法可能是也可能不是空的(对不起,如果这是一个无可救药的难以理解的句子)。 这是代码,如果它使事情更清晰:

    public void Inform(Room north, Room south, Room east, Room west)
    {
        this.north = north;
        this.south = south;
        this.east = east;
        this.west = west;
        node.Inform(north.GetNode(), south.GetNode(),
                    east.GetNode(), west.GetNode());
    }

基本上,我想知道是否有一种快速简便的方法来检查对象是否为 null,并简单地将"null"传递到条件之外的方法中——我宁愿不必显式编码所有 16 种可能的 null/非 null 变体。

编辑:为了回应混淆,我想澄清这一点:大多数情况下,我传递给方法的对象不会为空。 通常,Room存在北、南、东和西的对象,如果Room存在,GetNode() 方法将返回相应的对象。 我想确定是否存在给定Room以避免在尝试进行方法调用时出现空引用。

在 C# 中标识空对象

创建扩展方法

static Node GetNodeOrNull(this Room room)
{
  return room == null ? null : room.GetNode();
}
 public void Inform(Room north, Room south, Room east, Room west)
    {
        this.north = north;
        this.south = south;
        this.east = east;
        this.west = west;
        node.Inform(GetNode(north), GetNode(south),
                    GetNode(east),GetNode(west));
    } 
    private Node GetNode(Room room)
    {
        return room == null ?  null : room.GetNode();
    }

忽略其余代码(我必须:)) - 您可以开始使用 Null 模式。 例如,有一个 NullRoom 类,并让它的 GetNode() 返回一些有意义的东西。基本上从不允许实际的空引用。