Gosu语言中typeof与typeis关键字的区别是什么?
Gosu中
typeof与typeis的区别 核心差异
typeis:继承兼容检查some_obj typeis some_class用于判断对象是否是some_class的实例,或是some_class子类的实例,也支持检查是否是指定接口的实现类实例,属于宽泛的类型匹配逻辑。
代码示例:class Animal {} class Dog extends Animal {} interface Pet {} class Cat extends Animal implements Pet {} let dog = new Dog() let cat = new Cat() print(dog typeis Animal) // 输出 true(Dog是Animal的子类) print(cat typeis Pet) // 输出 true(Cat实现了Pet接口) print(dog typeis Dog) // 输出 true(精确匹配自身类型)typeof ==:精确类型匹配typeof some_obj会返回对象的精确运行时类型,用==和some_class比较时,只有当对象的类型和some_class完全一致(不包含子类、接口实现类)时才返回true,属于严格的类型匹配逻辑。
代码示例:class Animal {} class Dog extends Animal {} interface Pet {} class Cat extends Animal implements Pet {} let dog = new Dog() let cat = new Cat() print(typeof dog == Animal) // 输出 false(Dog是子类,不是Animal本身) print(typeof cat == Pet) // 输出 false(Pet是接口,Cat是实现类) print(typeof dog == Dog) // 输出 true(精确匹配自身类型)
一句话总结
typeis判断对象是否属于目标类型的继承/实现体系内,typeof ==只判断对象的类型是否和目标类型完全一致。
内容的提问来源于stack exchange,提问作者Matt Campbell
相关产品推荐
相关产品推荐

