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

2020-05-21 09:17发布

How can I determine whether an object is of a class or not in the Dart language?

I'm looking to do something like the following:

if (someObject.class.toString() == "Num") {
    ...
}

And what is the returned value type? Will it have to be a String?


The mirror library has been up and down and seems to be subject to rapid change right now, as the one thing I did find simply did not work as shown.

2条回答
老娘就宠你
2楼-- · 2020-05-21 09:58
  • 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)
    
查看更多
贼婆χ
3楼-- · 2020-05-21 10:05

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
查看更多
登录 后发表回答