【问题标题】:What does the question mark mean in GSP/Grails?问号在 GSP/Grails 中是什么意思?
【发布时间】:2011-06-02 15:57:01
【问题描述】:

我在生成的 GSP 页面中看到了这一点。 是什么意思?

<g:textField name="name" value="${phoneInstance?.name}" />

【问题讨论】:

    标签: grails groovy operators gsp


    【解决方案1】:

    它是“安全导航运算符”,它是一个 Groovy 功能​​,可以简洁地避免空指针异常。见http://docs.groovy-lang.org/latest/html/documentation/index.html#_safe_navigation_operator

    在这种情况下,如果 phoneInstance 为 null,则它不会尝试获取 name 属性并导致 NPE - 它只是将字段标记的值设置为 null。

    【讨论】:

    • 谢谢!我已经在谷歌上搜索了一段时间,但没有找到答案。
    • 为了更酷,您还可以使用 Elvis 运算符添加一个合理的默认值,例如:${phoneInstance?.number?:'+44'} Rock groovy with the king baby!
    【解决方案2】:

    ? 运算符允许在 Groovy(以及因此,GSP)中使用空值。例如,通常在 gsp 中,

    <g:field name="amount" value="${priceDetails.amount}" />
    

    如果priceDetails 为空,则会抛出NullPointerException

    如果我们改用? 运算符...

    <g:field name="amount" value="${priceDetails?.amount}" /> 
    

    现在${priceDetails?.amount} 的值为空,而不是抛出空指针异常。

    【讨论】:

      【解决方案3】:

      这是 Groovy 中非常重要的特性。如果对象为空(即, “phoneInstance”为空)然后它提供“空”值。这项特征 被称为“安全导航操作员”。只要我们使用这个特性,就不需要检查object("phoneInstance")是否为null。

      【讨论】:

        【解决方案4】:

        如果左侧的对象为空,安全导航运算符 (?.) 返回空,否则返回该对象右侧成员的值。所以phoneInstance?.name 只是phoneInstance == null ? null : phoneInstance.name 的简写

        例如:

        a = x?.y
        

        只是以下的简写:

        a = (x == null ? null : x.y)
        

        简写为:

        if(x == null){
            a = null
        } else {
            a = x.y
        }
        

        【讨论】:

          猜你喜欢
          • 2014-07-28
          • 1970-01-01
          • 1970-01-01
          • 2012-04-19
          • 2015-04-05
          • 2010-09-29
          • 2011-04-18
          • 2015-02-13
          • 2018-06-23
          相关资源
          最近更新 更多