C# 如何在C中以优雅的方式测试对象的null?

C# 如何在C中以优雅的方式测试对象的null?,c#,null,C#,Null,我想测试Output.ScriptPubKey.Addresses数组是否为null,然后将其分配给参数列表。如果为null,则我希望将参数值设置为0,否则使用数组中的项数 我在下面写的感觉既笨拙又冗长,有没有更优雅的方式 int addressCount; if (Output.ScriptPubKey.Addresses == null) { addressCount = 0; } else { addressCount = Output.ScriptPubKey.Addresses

我想测试Output.ScriptPubKey.Addresses数组是否为null,然后将其分配给参数列表。如果为null,则我希望将参数值设置为0,否则使用数组中的项数

我在下面写的感觉既笨拙又冗长,有没有更优雅的方式

int addressCount;
if (Output.ScriptPubKey.Addresses == null) { addressCount = 0; } else {
    addressCount = Output.ScriptPubKey.Addresses.Length;
}
var op = new DynamicParameters();
op.Add("@AddressCount", addressCount);
过去的代码是:

op.Add("@AddressCount", Output.ScriptPubKey.Addresses.Length);
但有时地址数组是空的。

您希望运算符与运算符组合:

int addressCount = Output.ScriptPubKey.Addresses?.Length ?? 0;
左手边的??除非结果为null,否则将使用运算符,在这种情况下,它将使用0。这个对null求值,如果潜在链的任何部分求值为null,则所有部分都将求值为null。因此,它会短路,并允许您编写如下表达式。

您希望运算符与运算符组合:

int addressCount = Output.ScriptPubKey.Addresses?.Length ?? 0;
左手边的??除非结果为null,否则将使用运算符,在这种情况下,它将使用0。这个对null求值,如果潜在链的任何部分求值为null,则所有部分都将求值为null。因此,它会短路,并允许您编写这样的表达式。

op。Add@AddressCount,Output.ScriptPubKey.Addresses?长度??0;作品。Add@AddressCount,Output.ScriptPubKey.Addresses?长度??0;