Dart 中是否有像 Java/Kotlin 中的 Class<T> 这样的通用类型?

Is there a generic Type in Dart like Class<T> in Java/Kotlin?

在 Kotlin 中我可以做类似的事情:

var myType : KClass<String>? = null

并且可以像这样分配给它:

myType = String::class

但不喜欢:

myType = Int::class // Type mismatch: inferred type in KClass<Int> but KClass<String>? was expected

Dart 中有类似的东西吗?我知道 Type 类型,但它不是通用的,虽然它可以表示 StringList<int> 我似乎无法编写与我的 Kotlin 示例类似的代码:

Type? t = null;

我可以分配给它:

t = String;

还有:

t = int;

但我希望第二个示例编译失败。我需要某种 Type<String>。这在 Dart 中可行吗?

我认为这是你能得到的最好的:

void main() {
  aFunction<String>(String, '');
  aFunction<String>(String, 1);
}

void aFunction<V>(Type type, V value) {
  print(value.toString());
}

如果你 运行 在飞镖板上看到这个,你会看到

aFunction<String>(type, 1);

不编译。

但这并不是很有效,因为 Dart 无法猜测类型,您必须手动指定泛型。

I'm using Dart 2.17

Type class 不是通用的,不支持子类型检查(或任何其他合理的 type-related 操作)。没有办法用它来做你想做的事。

所以,不要。反正也没用。但是,在 Dart 中,您可以创建自己的 own 实际有用的类型表示,因为 Dart 不会删除类型参数,然后您可以要求使用您的代码的人来代替它。

说:

class MyType<T> implements Comparable<MyType>{ // Or a better name.
  const MyType();
  Type get type => T;
  bool operator >=(MyType other) => other is MyType<T>;
  bool operator <=(MyType other) => other >= this;
  bool isInstance(Object? object) => object is T;
  R runWith<R>(R Function<T>() action) => action<T>();
  @override
  int get hashCode => T.hashCode;
  @override
  bool operator==(Object other) => other is MyType && T == other.type;
}

有了它你可以写:

MyType<String?> type;
type = MyType<Null>(); // valid
type = MyType<String>(); // valid
type = MyType<Never>(); // valid
type = MyType<int>; // EEEK! compile-time error

您可以在需要将类型存储为值的地方使用它。

事实是,大多数时候您可以只使用类型变量来代替,创建一个实际值来表示类型是多余的。 因此,首先 尝试只使用类型参数,而不是传递 TypeMyType 对象。仅当失败时,您才应考虑使用 MyType。使用 Type 可能是一个错误,因为它除了做 == 检查外没有任何用处,这与面向对象的子类型包含的想法相反。