【问题标题】:Kotlin access backing field in other place?Kotlin 在其他地方访问支持字段?
【发布时间】:2017-10-25 02:50:09
【问题描述】:

我发现它只能访问set或get中的backing field。有什么方法可以访问课堂上其他地方的backing field吗? 例如。

var width:Int=0
get() {
    return field*10;
}
set(value) {
    field=value/10;
}

我想访问真正的价值,但不是它的倍数 10

当我使用 c# 时,没有字段关键字,所以总是需要声明一个新变量来存储真实数据。在前面的示例中,它看起来像

private var _width=0;
var width:Int
get() {
    return _width*10;
}
set(value) {
    _width=value/10;
}

所以如果我想访问类中的真实值,我可以访问 _value。 但是在 kotlin 中,是否有某种方式可以在没有这些冗长声明的情况下访问支持字段?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    没有。您的 C# 示例在 Kotlin 中运行良好,它被称为 backing property

    【讨论】:

      【解决方案2】:

      Kotlin,您可以使用支持属性

      支持属性

      如果你想做一些不适合这种“隐式支持字段”方案的事情,你总是可以退回到拥有一个支持属性:

      private var _table: Map<String, Int>? = null
      public val table: Map<String, Int>
          get() {
              if (_table == null) {
                  _table = HashMap() // Type parameters are inferred
              }
              return _table ?: throw AssertionError("Set to null by another thread")
          }
      

      在所有方面,这与 Java 中的相同,因为使用默认 getter 和 setter 访问私有属性已经过优化,因此不会引入函数调用开销。

      【讨论】:

        猜你喜欢
        • 2015-12-02
        • 2020-07-03
        • 2017-08-30
        • 1970-01-01
        • 2020-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多