kotlin - 如何在 kotlin 中为视频游戏实现 getComponent(/*Class*/) 方法
问题描述
我正在用 kotlin 编写,为 Android 开发基于文本的 RPG 游戏。我目前正在开发带有策略/实体组件设计的对象系统。我被困在 getComponent 函数上,不知道我在做什么
我需要一个方法来接受对 Class 类型的引用,然后将其与所有组件实例的类类型进行比较。
我尝试过使用泛型、KClass、Java 类型,但找不到答案。
我的主要问题是“as”运算符。我不知道它接受什么。
到目前为止我得到的是:
fun getComponent(clazz : KClass<*>) : Component? {
for(component in components) {
if(component is clazz) {
return component
}
}
return null
}
这段代码是错误的。IntelliJ 提醒我 clazz 不存在,因为它不是一个实际的类。
解决方案
您有一个KClass
实例,它是一个表示类型的运行时对象,用于反射。您在这里有两个主要选择。您可以像这样使用reified generics,这样您就可以完全避免使用反射:
inline fun <reified T : Component> getComponent() : T? {
for(component in components) {
if(component is T) {
return component
}
}
return null
}
可以像这样调用此方法:
getComponent<SomeClass>()
或者,您可以使用KClass.isInstance:
fun getComponent(clazz : KClass<*>) : Component? {
for(component in components) {
if(clazz.isInstance(component)) {
return component
}
}
return null
}
您也可以使用泛型和强制转换使这更方便一些:
fun <T : Component> getComponent(clazz : KClass<*>) : T? {
for(component in components) {
if(clazz.isInstance(component)) {
return component as T
}
}
return null
}
对于这两者,用法是相同的:
getComponent(SomeClass::class)
推荐阅读
- reactjs - 尝试在 Reactjs 中获取股票数据时为股票代码创建搜索功能
- python - 从终端运行脚本时 Altair 不显示图表?
- asp.net - 我可以从解决方案以外的文件夹在 ASP.NET MVC 中制作捆绑包吗?
- swift - 如何在 Swift 中编写一个使用 Comparable 的全局函数
- r - 如果列名不存在,为什么 DT 包中的 formatCurrency() 会出错?
- javascript - 如何将 vanilla javascript 小部件创建为 Web 组件并动态导入页面?
- python - 保存 json 添加反斜杠
- python - 如何对 Pandas 中的名词短语进行情感分析?
- mysql - 仅获取 1 个月以上的 mysql 记录
- python - 类型错误:Iniciar() 缺少 1 个必需的位置参数:“数据”并且附加失败