我正在进行一个方法调用,它将另外四个方法调用的结果作为参数 - 但是进行这些调用的方法可能会也可能不会为空(对不起,如果这是一个绝对无法理解的句子).这是代码,如果它使事情更清楚:
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());
}
Run Code Online (Sandbox Code Playgroud)
基本上,我想知道是否有一种快速简便的方法来检查一个对象是否为null并且除了条件之外简单地将'null'传递给方法 - 我宁愿不必为null的所有16种可能变体显式编码不是空的.
编辑:为了回应混淆,我想澄清一下:大多数时候我传入方法的对象不会为空.通常,Room对象存在于北,南,东和西,如果Room存在,GetNode()方法将返回适当的对象.我想确定一个给定的Room存在是否在尝试进行方法调用时避免空引用激活.
创建扩展方法
static Node GetNodeOrNull(this Room room)
{
return room == null ? null : room.GetNode();
}
Run Code Online (Sandbox Code Playgroud)