How to tell if an object is an instance of a class

筅森魡賤 提交于 2019-12-03 01:24:20
Eliran Malka
  • By using the is and is! operators, like this:

    if (someObject is T)
    

    From the documentation:

    The is and is! operators are handy for checking types. The result of obj is T is true if obj implements the interface specified by T. For example, obj is Object is always true.

  • Using the Mirrors API (see this example):

    Expect.equals('T', someObject.simpleName)
    
Vadim Tsushko

Recently Object got runtimeType getter. So, now we may not only compare type of object with another type, but actually get the class name of an object. As in:

myObject.runtimeType.toString()

Furthermore, in the current version of Dart, you can now skip toString operation and directly compare runtimeType of object with target type as in

myObject.runtimeType == int

or

myObject.runtimeType == Animal
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!