【问题标题】:How to test an object for null in an elegant way in C#?如何在 C# 中以优雅的方式测试对象是否为 null?
【发布时间】:2019-01-02 21:27:25
【问题描述】:

我想测试Output.ScriptPubKey.Addresses 数组是否为空,然后将其分配给参数列表。如果为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);

但有时Addresses 数组为空。

【问题讨论】:

  • op.Add("@AddressCount", Output.ScriptPubKey.Addresses?.Length ?? 0);

标签: c# null


【解决方案1】:

您希望 null-coalescing 运算符与 null conditional 运算符结合使用:

int addressCount = Output.ScriptPubKey.Addresses?.Length ?? 0;

除非结果为空,否则将使用?? 运算符的左侧,在这种情况下它将使用0?. 对 null 进行评估,如果(潜在链)的任何部分评估为 null,则所有部分都评估为 null。因此它会短路并允许您编写这样的表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2012-11-04
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多