我如何测试一个对象是否是 D 中特定类的实例?

发布于 2024-12-28 13:07:48 字数 84 浏览 1 评论 0原文

我如何测试一个对象是否是 D 中特定类的实例?

类似于 Javascript 的 instanceof 关键字?

How do i test that an object is an instance of a particular class in D?

Something akin to Javascript's instanceof keyword?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

老旧海报 2025-01-04 13:07:48

使用强制转换。当您尝试转换为不是其实例的子类时(如 C++ 的dynamic_cast),它会返回空引用。

auto a = new Base;
auto b = cast(Child) a;
assert(b is null);

a = new Child;
auto c = cast(Child) a;
assert(c !is null);

Use cast. It returns a null reference when you attempt to cast to a subclass it isn't an instance of (like C++'s dynamic_cast).

auto a = new Base;
auto b = cast(Child) a;
assert(b is null);

a = new Child;
auto c = cast(Child) a;
assert(c !is null);
此岸叶落 2025-01-04 13:07:48

typeid 表达式 可以告诉您实例是否属于某种确切类型(无需考虑继承层次结构):

class A {}

class B : A {}

void main()
{
        A a = new B();
        // dynamic
        assert( typeid(a) == typeid(B) );
        // static
        assert( typeid(typeof(a)) == typeid(A) );
}

typeid expression can tell you if instance is of some exact type (without considering inheritance hierarchy):

class A {}

class B : A {}

void main()
{
        A a = new B();
        // dynamic
        assert( typeid(a) == typeid(B) );
        // static
        assert( typeid(typeof(a)) == typeid(A) );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文