当前位置: 首页 > 知识库问答 >
问题:

省道空/假/空检查:如何写这个更短?

哈和惬
2023-03-14

这是我的true代码,除了空字符串、null和false之外:

if (routeinfo["no_route"] == "" || routeinfo["no_route"] == null || routeinfo["no_route"] == false) {
    // do sth ...
}

这是我的true代码,除了空字符串、null、false或零之外:

if (routeinfo["no_route"] == "" || routeinfo["no_route"] == null || routeinfo["no_route"] == false || routeinfo["no_route"] == 0) {
    // do sth...
}

我怎么能用Dart写得更短?还是不可能?

共有3个答案

卫飞
2023-03-14
  • 这个答案成立,除了isNullisNotNull。当将来在dart/flutter中引入Null Security时,它们不再提供类型提升。
  • 其他帮助程序,如isNullOr空不提供类型提升,因为它们与调用站点相比处于不同的(子)范围内。
  • 我个人的意见是,您可以删除isNullisNotNull,但保留其他助手,因为您不应该期望他们为您进行类型推广。
  • 这是因为最后在Dart/FLATTER中引入了零安全。但截至2020年10月,此功能仍不适用于dart/FLUTER的稳定版本。查看快速指南零安全或彻底了解零安全

这里有一个演示为什么isNull==null)和isNotNull!=null)的封装/helper-getter是一个非常大的问题:

// Promotion works
int definitelyInt(int? aNullableInt) {
  if (aNullableInt == null) { // Promote variable `aNullableInt` of Nullable type `int?` to Non-Nullable type `int`
    return 0;
  }
  return aNullableInt; // Can't be null! This variable is promoted to non-nullable type `int`
}

当您使用的dart版本中提供了“Null Safety”时,上述代码中的类型提升就起作用了!然而:

// Promotion does NOT work!!!
int definitelyInt(int? aNullableInt) {
  if (aNullableInt.isNull) { // does NOT promote variable `aNullableInt` of Nullable type `int?`
    return 0;
  }
  return aNullableInt; // This variable is still of type `int?`!!!
}

上面的方法不起作用,因为空检查==null!=null封装在一个子范围(不同的堆栈框架)中,并且不推断在定义Int范围内具有这种“提升”效果。

这是一个使用getter而不是实例/类方法并涵盖空白、isNull和isNotNull的修改版本。

现在它还可以解释空列表和地图!

为安全性和模块化/可运维性添加了私有获取器。

更新了答案以修复Map的特定问题,空时处理不正确!因为Map不是Iterable。通过引入_isMapObjectEmptyU解决了这个问题

extension TextUtilsStringExtension on String {
  /// Returns true if string is:
  /// - null
  /// - empty
  /// - whitespace string.
  ///
  /// Characters considered "whitespace" are listed [here](https://stackoverflow.com/a/59826129/10830091).
  bool get isNullEmptyOrWhitespace =>
      this == null || this.isEmpty || this.trim().isEmpty;
}

/// - [isNullOrEmpty], [isNullEmptyOrFalse], [isNullEmptyZeroOrFalse] are from [this StackOverflow answer](https://stackoverflow.com/a/59826129/10830091)
extension GeneralUtilsObjectExtension on Object {
  /// Returns true if object is:
  /// - null `Object`
  bool get isNull => this == null;

  /// Returns true if object is NOT:
  /// - null `Object`
  bool get isNotNull => this != null;

  /// Returns true if object is:
  /// - null `Object`
  /// - empty `String`s
  /// - empty `Iterable` (list, set, ...)
  /// - empty `Map`
  bool get isNullOrEmpty =>
      isNull ||
      _isStringObjectEmpty ||
      _isIterableObjectEmpty ||
      _isMapObjectEmpty;

  /// Returns true if object is:
  /// - null `Object`
  /// - empty `String`
  /// - empty `Iterable` (list, map, set, ...)
  /// - false `bool`
  bool get isNullEmptyOrFalse =>
      isNull ||
      _isStringObjectEmpty ||
      _isIterableObjectEmpty ||
      _isMapObjectEmpty ||
      _isBoolObjectFalse;

  /// Returns true if object is:
  /// - null `Object`
  /// - empty `String`
  /// - empty `Iterable` (list, map, set, ...)
  /// - false `bool`
  /// - zero `num`
  bool get isNullEmptyFalseOrZero =>
      isNull ||
      _isStringObjectEmpty ||
      _isIterableObjectEmpty ||
      _isMapObjectEmpty ||
      _isBoolObjectFalse ||
      _isNumObjectZero;

  // ------- PRIVATE EXTENSION HELPERS -------
  /// **Private helper**
  ///
  /// If `String` object, return String's method `isEmpty`
  ///
  /// Otherwise return `false` to not affect logical-OR expression. As `false` denotes undefined or N/A since object is not `String`
  bool get _isStringObjectEmpty =>
      (this is String) ? (this as String).isEmpty : false;

  /// **Private helper**
  ///
  /// If `Iterable` object, return Iterable's method `isEmpty`
  ///
  /// Otherwise return `false` to not affect logical-OR expression. As `false` denotes undefined or N/A since object is not `Iterable`
  bool get _isIterableObjectEmpty =>
      (this is Iterable) ? (this as Iterable).isEmpty : false;

  /// **Private helper**
  ///
  /// If `Map` object, return Map's method `isEmpty`
  ///
  /// Otherwise return `false` to not affect logical-OR expression. As `false` denotes undefined or N/A since object is not `Map`
  bool get _isMapObjectEmpty => (this is Map) ? (this as Map).isEmpty : false;

  /// **Private helper**
  ///
  /// If `bool` object, return `isFalse` expression
  ///
  /// Otherwise return `false` to not affect logical-OR expression. As `false` denotes undefined or N/A since object is not `bool`
  bool get _isBoolObjectFalse =>
      (this is bool) ? (this as bool) == false : false;

  /// **Private helper**
  ///
  /// If `num` object, return `isZero` expression
  ///
  /// Otherwise return `false` to not affect logical-OR expression. As `false` denotes undefined or N/A since object is not `num`
  bool get _isNumObjectZero => (this is num) ? (this as num) == 0 : false;
}

这假定Dart 2.7或更高版本支持扩展方法。

上面是两个扩展类。一个用于Object,一个用于String。将它们单独/一起放在一个文件中,并在调用站点文件中导入文件/文件。

来自Swift,我倾向于使用扩展,如user@Benjamin Menrad的答案,但在适用时使用getter而不是方法/函数——镜像Dart的计算属性,如字符串。isEmpty(空)。

来自C#,我喜欢字符串的助手方法IsNullOrWhiteSpace。

我的版本融合了上述两个概念。

可以随意重命名扩展类。我倾向于这样命名他们:

XY扩展

在哪里:

  • X是文件/作者/应用程序/唯一名称。
  • Y是正在扩展的类型的名称。

名称示例:

  • MyAppIntExtension
  • 扩展名
  • TextUtilsStringExtension
  • OHProviderExtension

为什么私有getters而不是简单的this==null||this == '' || this == [] || this==0||! this

  • 我认为这样更安全,因为它首先将对象强制转换为我们想要比较其值的正确类型
  • 更模块化,因为更改是私有getter中的核心,任何修改都会反映在每个地方
  • 如果私有getter中的类型检查失败,则返回false,这不会影响根逻辑OR表达式的结果

慕容坚
2023-03-14

你可以做的

if (["", null, false, 0].contains(routeinfo["no_route"])) {
  // do sth
}
陶富
2023-03-14

如果您的要求只是空的或空的(就像我在搜索结果中看到这个标题时一样),您可以使用Dart的安全导航操作符使其更简洁:

if (routeinfo["no_route"]?.isEmpty ?? true) {
  // 
}

哪里

  • isEmpty检查空字符串,但如果routeinfo为null,则不能在null上调用isEmpty,因此我们使用

如果地图是可空类型,则必须安全导航:

if (routeinfo?["no_route"]?.isEmpty ?? true) {
  //
}
 类似资料:
  • 下面的代码引发NullPointerException。即使有

  • 本文向大家介绍sitecore 空/空检查,包括了sitecore 空/空检查的使用技巧和注意事项,需要的朋友参考一下 示例 IsNotNull 这是一种非常简单且流行的方法,用于检查项目是否不为空。它只是检查传入的对象是否为空。 IsNotNullOrEmpty 这与上面的IsNotNull相同,但是适用于字符串值而不是对象。 一片空白 这只是该IsNotNull()方法的逆过程。此方法断言该对

  • 问题内容: 我定义一个结构… 有时我给它分配一个空的会话(因为nil不可能) 然后,我想检查一下是否为空: 显然这是行不通的。我该怎么写? 问题答案: 您可以使用==与零值复合文字进行比较,因为所有字段都是可比较的: 游乐场的例子 由于存在歧义,因此在if条件下,在组合文字周围需要括号。 上面的用法适用于所有字段都是可比较的结构。如果该结构包含不可比较的字段(切片,映射或函数),则必须将这些字段一

  • 我定义了一个结构… 有时我给它分配一个空会话(因为不可能为零) 然后我想检查一下,如果它是空的: 显然这是行不通的。我怎么写?

  • 我有一小段代码。我想用更好的方式写它,用更少的嵌套支票。我怎样才能实现呢? 有没有什么简洁的方法可以让我用Java 8重写上面的代码呢?

  • 问题内容: 我想知道此代码对于检查数组是否为空是否有效,还是应该检查null? 谢谢! 问题答案: 在数组类中,我们有一个定义为“ length”的静态变量,该变量保存数组对象中的元素数。您可以使用它来找到长度为: