弱引用使用

作者: 不正经的创作者 | 来源:发表于2020-05-19 15:31 被阅读0次

弱引用使用


  class Weak<T : Any>(initializer: () -> T?) {
      var weakReference = WeakReference<T?>(initializer())

      constructor():this({
          null
      })

      operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
          Log.d("Weak Delegate","-----------getValue")
          return weakReference.get()
      }

      operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
          Log.d("Weak Delegate","-----------setValue")
          weakReference = WeakReference(value)
      }

  }
  //需要指定初始值的情况
          //自动推断出泛型
          var act by Weak{
              context
          }
          //也可以指定泛型,一种是给属性指定类型,必须为可null的
          var act: Activity? by Weak {
              context
          }
          //第二种是为Weak指定泛型,不可null的
          var act by Weak<Activity> {
              context
          }

  //不指定初始值的情况,此时必须指定泛型
          var act:Activity? by Weak()
          或者
          var act by Weak<Activity>()

相关文章

网友评论

    本文标题:弱引用使用

    本文链接:https://www.haomeiwen.com/subject/rlebohtx.html