使用类型引用作为变量进行 Dart 类型检查

1 typechecking dart

我正在尝试使用存储为变量的类型引用在 Dart 中进行类型检查。像这样的事情:

    class Thingamajig {}
    
    bool method(dynamic object) {
      var Type type = Thingamajig;
      if (object is type) { //gives error: type_test_with_non_type
        doSomething();
      }
    }
Run Code Online (Sandbox Code Playgroud)

我的用例需要 的子类型检查功能is,所以runtimeType还不够。我怎样才能做到这一点并消除错误?

编辑:我的真正意图是将该类型作为 Flutter 小部件测试的 Finder 类实现上的实例变量。我可以用这样的方法解决这个问题:

    class Thingamajig {}
    
    bool method(dynamic object) {
      var Type type = Thingamajig;
      if (object is type) { //gives error: type_test_with_non_type
        doSomething();
      }
    }
Run Code Online (Sandbox Code Playgroud)

或者

if (type == MyClass && object is MyClass)
if (type == MyOtherClass && object is MyOtherClass)
Run Code Online (Sandbox Code Playgroud)

但我希望有一个更清洁的选择。

cam*_*024 5

您可以简单地将类型文字传递到表达式中is,它就会起作用:

var type = MyCustomClass;
if (object is type) ...  // "type" is not a type
if (object is MyCustomClass)  // works fine, including subtypes
Run Code Online (Sandbox Code Playgroud)

如果你不能这样做(也许你想将类型作为参数传递),你可以使用类型参数:

bool checkType<T>(dynamic object) {
  if (object is T) ...  // works fine
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您希望类型在运行时是动态的,那么您就不太走运了。如果这就是您想要的,也许一些有关您想要的原因的背景信息将有助于提供更好的答案。