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

后端 未结 3 1563
时光说笑
时光说笑 2021-02-02 07:45

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.to         


        
相关标签:
3条回答
  • 2021-02-02 08:07
    • 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)
      
    0 讨论(0)
  • 2021-02-02 08:08

    Here is a simple explanation with a solution.

    You have:

    Object obj =t1;
    where t1 is an object of class T.

    And you have other object T called t.

    T t = new T();

    How to check if obj is the same type of t ?

    Solution:

    if(obj is t)
         print('obj is typeof t')
       else print('obj is not typeof t') 
    
    0 讨论(0)
  • 2021-02-02 08:12

    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
    
    0 讨论(0)
提交回复
热议问题