c# - 如何在 C# 中以优雅的方式测试对象是否为 null?

标签 c# null

我想测试 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/

相关文章:

c# - 公共(public)常量字符串?

c# - Automapper 5.0.0 缺少 SourceValue(自定义转换器)

c# - datareader 失败但不引发异常 c#

带有空参数的 Erlang ODBC 参数查询

database - 将具有空值的大型 CSV 数据集添加到 postgres 数据库

ios - Swift 1.2 - 将可选类型数组中的元素设置为 nil——传入时不允许吗?

php - 如何在 PHP PDO 中插入空字符串而不是 null

c# - 使用 .Net Reflector 或其他工具确定 exe 的原始构建位置/路径

c# - 变量名称长度对 C# 性能有影响吗?

c++ - 取消引用 nullptr 时编译器不会发出警告