类型判断(instanceof)

演示运行期类型检查;Go 用类型断言、Rust 以枚举+模式匹配取代。

C C23

C23
#include <stdio.h>

// C 没有运行时类型信息;手写"类型标签"模拟 instanceof
typedef enum {
    TYPE_ANIMAL,
    TYPE_DOG
} TypeTag;

typedef struct {
    TypeTag type;
} Animal;

typedef struct {
    Animal base; // 继承:基类部分位于子结构体头部
} Dog;

int main(void) {
    Dog dog = { { TYPE_DOG } };

    printf("bool(%s)\n", dog.base.type == TYPE_DOG ? "true" : "false");
    // 沿"继承链"上溯:子类型标签也满足父类型检查
    printf("bool(%s)\n", dog.base.type == TYPE_ANIMAL || dog.base.type == TYPE_DOG ? "true" : "false");
    printf("bool(false)"); // C 没有 Object 根类型;第三例仅作对照
    return 0;
}
输出
bool(true)
bool(true)
bool(false)

C++ C++26

C++26
#include <iostream>
class Animal { public: virtual ~Animal() = default; };
class Dog : public Animal {};
class Cat : public Animal {};
int main() {
    Dog dog;
    Animal& a = dog; // 上转型
    std::cout << std::boolalpha;
    std::cout << (dynamic_cast<Dog*>(&a) != nullptr) << "\n";   // 下转型检查:是 Dog
    std::cout << (dynamic_cast<Animal*>(&dog) != nullptr) << "\n"; // 上转型始终成立
    std::cout << (dynamic_cast<Cat*>(&a) != nullptr) << "\n";   // 无关子类:false
    return 0;
}
输出
true
true
false

C# v11.0.100

v11.0.100
var dog = new Dog();
Console.WriteLine(dog is Dog);
Console.WriteLine(dog is Animal); // 沿继承链上溯
Console.WriteLine(dog is string); // 无关类型

class Animal {}
class Dog : Animal {}
输出
True
True
False

Go v1.27.4

v1.27.4
package main

import "fmt"

type Animal struct{ Name string }
type Dog struct{ Animal }

func describe(x any) string {
    if d, ok := x.(Dog); ok { // 类型断言:检查并提取具体类型
        return "is a Dog: " + d.Name
    }
    return "not a Dog"
}

func main() {
    var x any = Dog{Animal: Animal{Name: "Rex"}}
    fmt.Println(describe(x))
    fmt.Println(describe("text"))

    switch v := x.(type) { // 类型 switch:一次检查多种类型
    case Dog:
        fmt.Println("switch hit Dog:", v.Name)
    case string:
        fmt.Println("switch hit string:", v)
    default:
        fmt.Println("unknown type")
    }
}
输出
is a Dog: Rex
not a Dog
switch hit Dog: Rex

Java v27.0.1

v27.0.1
public class Main {
    static class Animal {}
    static class Dog extends Animal {}
    public static void main(String[] args) {
        Animal a = new Dog();
        System.out.println(a instanceof Dog);
        System.out.println(a instanceof Animal); // 沿继承链上溯
        // 与无关类(如 String)比较是编译错误;
        // 与接口比较合法:Animal 未实现 Runnable,结果为 false
        System.out.println(a instanceof Runnable);
        // Java 16+ 支持模式变量:if (a instanceof Dog d) { d.bark(); }
    }
}
输出
true
true
false

JavaScript v26.13.1

v26.13.1
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog);
console.log(dog instanceof Animal); // 沿原型链上溯
console.log(typeof dog); // 原始类型检查用 typeof
console.log(typeof "text");
输出
true
true
object
string

PHP v8.6.0

v8.6.0
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Dog);
var_dump($dog instanceof Animal); // 沿继承链上溯
var_dump($dog instanceof stdClass);
输出
bool(true)
bool(true)
bool(false)

Python v3.15.2

v3.15.2
class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))  # 考虑继承链(鸭子类型代码中更常用)
print(isinstance(dog, str))
# 精确类型(不含子类)用 type(dog) is Dog
输出
True
True
False

Rust v1.99.1

v1.99.1
// Rust 没有继承,也极少做运行时类型检查;
// 多态数据用枚举承载,经 match 分发(编译期穷尽检查)
enum Pet {
    Dog(String),
    Cat(String),
}

fn main() {
    let pets = [Pet::Dog(String::from("Rex")), Pet::Cat(String::from("Kitty"))];
    for p in &pets {
        match p {
            Pet::Dog(name) => println!("dog: {}", name),
            Pet::Cat(name) => println!("cat: {}", name),
        }
    }
    // trait 对象下转型可用 Any + downcast,但非惯用法
}
输出
dog: Rex
cat: Kitty

TypeScript v26.13.1

v26.13.1
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog);
console.log(dog instanceof Animal); // 沿原型链上溯
console.log(typeof dog); // 原始类型检查用 typeof
console.log(typeof "text");
输出
true
true
object
string

语言差异说明

C:无运行期类型信息(RTTI),示例以手写类型标签沿“继承链”判断模拟 instanceof。

C++:以 dynamic_cast + 空指针检查判断继承关系(基类需多态)。

Go:无继承,对接口值/any 用类型断言 x.(T) 与 type switch。

Java:instanceof(Java 16+ 支持 if (a instanceof Dog d) 模式变量直接绑定)。

JavaScript:instanceof 沿原型链检查,原始类型用 typeof。

PHP:instanceof(沿继承链检查)。

Python:isinstance(obj, cls) 同样考虑子类,type(x) is T 才是精确类型判断;更 Pythonic 的做法是鸭子类型。

Rust:无运行期类型判断的惯用法:以枚举 + match 模式匹配表达,编译器保证穷尽;trait 对象下转型可用 Any,但一般不推荐。