Switching on class type in Dart

后端 未结 1 1398
温柔的废话
温柔的废话 2021-01-03 19:36

I\'m looking to write a function in a Dart superclass that takes different actions depending on which subclass is actually using it. Something like this:



        
相关标签:
1条回答
  • 2021-01-03 20:06

    You can use the runtimeType in switch :

    class Foo {
      Foo getAnother(Foo foo) {
        switch (foo.runtimeType) {
          case Bar:
            return new Bar();
          case Baz:
            return new Baz();
        }
        return null;
      }
    }
    

    In the case statements the class name is use directly (aka. class literal). This gives a Type object corresponding to the class mentionned. Thus foo.runtimeType can be compared with the specified type.

    Note that you can not use generics for now in class literals. Thus case List<int>: is not allowed.

    0 讨论(0)
提交回复
热议问题