简体   繁体   English

将对象转换为特定类取决于何时调用

[英]cast an object into specific class depend on when called

I have a class that one of properties can has 2 different types, How can I cast that variable to one of those classes that I want? 我有一个类,其中一个属性可以具有2种不同的类型,如何将变量转换为我想要的那些类之一?

    class myObject{
        var type: Int
        var meta: Any? = null }

   var myobject:myObject=myObject()
        if(myobjetc.type ==1){
val myObject = (myobjetc.meta) as ObjectA
 Log.e("log",myObject.name)
}
        if(myobjetc.type ==2){
val myObject = (myobjetc.meta) as ObjectB
 Log.e("log",myObject.number)
}

problem is that it cant cast. 问题是它无法投射。

EDITED EDITED

class ObjectB: GsonBaseModel() {
var name: String? = null
}

    class ObjectA: GsonBaseModel() {
var number: Int? = null
}

You're almost there. 你快到了。 Either check for null, or better yet, use is or when and is 检查是否为null,或者更好,使用iswhenis

// as:
if(myobject.meta as ObjectA != null) Log.e("log", myobject.meta.name)
if(myobject.meta as ObjectB != null) Log.e("log", myobject.meta.number)

// is:
val meta = myobject.meta
if (meta is ObjectA) Log.e("log", meta.somePropertyOfObjectA)
if (meta is ObjectB) Log.e("log", meta.somePropertyOfObjectB)

// when:
when (myobject.meta) {
    is ObjectA -> Log.e("log", myobject.meta.name)
    is ObjectB -> Log.e("log", myobject.meta.number)
    else -> throw Exception()
}

However, this only works if the original type makes sense. 但是,这仅在原始类型有意义的情况下有效。 If meta is of class ObjectC, and neither ObjectA nor ObjectB inherit from it, then it won't help. 如果meta是ObjectC类的,而ObjectA和ObjectB都不从它继承,那么它将无济于事。 Without seeing your class code though, we can't help you there. 但是,如果看不到您的课程代码,我们将无法为您提供帮助。

But if that is the case, you may want to revisit your class design or code flow if the above won't work for you. 但是,在这种情况下,如果以上方法都不适合您,则可能需要重新访问类设计或代码流。

EDIT: After the class info was added to the Question, it looks like you'll want to the first option, the unsafe cast via as with a null check. 编辑:类信息添加到问题后,它看起来像你要第一个选项, 不安全投通过as一个空检查。

It looks like what you need is a sealed class 看起来您需要的是密封课程

sealed class Model() : GsonBaseModel()

class TypeA(val number: Int?) : Model()
class TypeB(val name: String?) : Model()

when (myObject) {
    is TypeA -> log(myObject.number)
    is TypeB -> log(myObject.name)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM