kotlin - 获取对调用函数的类的引用
问题描述
当我有两个类(A 和 B)并且 A 有一个名为 myFunA 的函数然后调用 myFunB(在 B 类内部)时,myFunB 中的代码是否可以获得对用于调用 myFunB 的类 A 的引用?我总是可以将引用作为参数传递,但我想知道 Kotlin 是否有办法让函数确定父调用者的实例。
class A {
fun myFunA() {
val b = B()
b.myFunB() {
}
}
}
class B {
fun myFunB() {
// Is it possible to obtain a reference to the instance of class A that is calling
// this function?
}
}
解决方案
你可以这样做:
interface BCaller {
fun B.myFunB() = myFunB(this@BCaller)
}
class A : BCaller {
fun myFunA() {
val b = B()
b.myFunB()
}
}
class B {
fun myFunB(bCaller: BCaller) {
// you can use `bCaller` here
}
}
如果您需要基于反射的方法,请阅读此。
推荐阅读
- c# - 我如何知道是什么可能导致强制断开与 ASP.NET WebApi 服务的连接?
- postgresql - PostgreSQL:第一个和最后一个之间的计算
- vue.js - vuetify.js:加载了 vue-router 的 v-form-textfield 不可见
- java - 如何检查一个字符串是否包含Java中所有重复的字母?
- python-3.x - 给定一个参数化测试,我怎样才能为所有参数只打印一次消息?
- azureservicebus - Masstransit Azure 服务总线和 DI 请求/响应模型
- ruby-on-rails - 使用 JSONAPI 在请求中发送文件
- c - 将值输入到结构化数组中的数组时出现分段错误
- flutter - 如何在 Flutter 中传递回调
- c# - PeekMessage TranslateMessage DispatchMessage。有没有办法在没有 EXTERN 的 .NET 中本地执行此操作?