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

Dart type checking with type reference as variable

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

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

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

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

if (type == MyClass && object is MyClass)
if (type == MyOtherClass && object is MyOtherClass)

switch (type) {
    case MyClass:
        if (object is MyClass) //do stuff
        break;
    case MyOtherClass:
        if (object is MyOtherClass) // do other stuff
        break;
}

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

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

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

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

bool checkType<T>(dynamic object) {
  if (object is T) ...  // works fine
}

但是,如果您希望您的类型在运行时是动态的,那您就有点不走运了。如果这是您想要的,也许一些关于您想要的原因的上下文有助于提供更好的答案。