-
Notifications
You must be signed in to change notification settings - Fork 779
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2019-07-26:什么是委托属性?请简要说说其使用场景和原理? #107
Comments
把一件事委托给其他人来做。如kotlin中的by |
居然没人说,很奇怪呀=.=
private val userId by UserIdDelegete() UserIdDelegete中 定义了 user id 的获取和设置方法 写的不一定对哈,用的不多,也记不住
原理的话不太好写,但是可以借助于 kotlin byteCode 工具来看自动生成的代码,类委托的话大家自己百度吧,简单对比一下属性委托 //源文件 class A {
private var name by Delegate()
}
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, 这里委托了 ${property.name} 属性"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$thisRef 的 ${property.name} 属性赋值为 $value")
}
} ByteCode 工具decompile的java文件
|
属性委托有些常见的属性操作,我们可以通过委托方式,让它实现,例如:
类委托可以通过类委托来减少 extend interface Base{
fun print()
}
case BaseImpl(var x: Int):Base{
override fun print(){
print(x)
}
}
// Derived 的 print 实现会通过构造函数的b对象来完成
class Derived(b: base): Base by b |
类委托: class A: Base by BaseImp() 实现一个接口了正好有一个类可以使用 属性委托:委托的类需要实现 getValue和setValue 函数加上operator关键字 委托延迟: by lazy ,lazy内只执行一次,后续只返回结果 委托工厂:主要需要实现ReadWriteProperty 接口 属性监听: Delegates.observable 无条件赋值 和Delegates.vetoable (有条件的赋值) |
这是来自QQ邮箱的假期自动回复邮件。
您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。
|
No description provided.
The text was updated successfully, but these errors were encountered: