我想测试 Output.ScriptPubKey.Addresses
数组是否为空,然后将其分配给参数列表。如果它为空,那么我想将参数值设置为 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);
但有时 Addresses
数组是空的。
最佳答案
你想要 null-coalescing运算符与 null conditional 结合运算符(operator):
int addressCount = Output.ScriptPubKey.Addresses?.Length ?? 0;
将使用 ??
运算符的左侧,除非结果为空,在这种情况下它将使用 0
。 ?.
针对 null 进行评估,如果(潜在链)的任何部分评估为 null,则所有部分评估为 null。因此它短路并允许您编写这样的表达式。
关于c# - 如何在 C# 中以优雅的方式测试对象是否为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54013392/