1. typeid和typeof

typeid用于获取一个表达式的类型信息,返回一个Type对象。typeof用于获取一个类型的信息,返回一个Type对象。

例子:

import std.stdio;

class MyClass {
    int x;
    string y;
}

void main() {
    int a = 1;
    float b = 2.0;
    string c = "hello";
    MyClass d = new MyClass();

    writeln(typeid(a));
    writeln(typeid(b));
    writeln(typeid(c));
    writeln(typeid(d));
    writeln(typeof(MyClass));
}

输出:

int
float
string
MyClass
MyClass
  1. stringof和is

stringof用于获取一个类型的名称,返回一个string对象。is用于检查一个表达式的类型是否是指定的类型,返回一个bool值。

例子:

import std.stdio;

class MyClass {
    int x;
    string y;
}

void main() {
    int a = 1;
    float b = 2.0;
    string c = "hello";
    MyClass d = new MyClass();

    writeln(stringof(a));
    writeln(stringof(b));
    writeln(stringof(c));
    writeln(stringof(d));

    writeln(a is int);
    writeln(b is float);
    writeln(c is string);
    writeln(d is MyClass);
}

输出:

int
float
string
MyClass
true
true
true
true

可以看出,stringof获取的是类型的名称,而不是Type对象。is用于检查类型是否匹配

dlang语言typeidtypeofstringofis等关于类型判断的用法和区别给出几个完整可运行的例子进行讲解

原文地址: https://www.cveoy.top/t/topic/fkR0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录