gpt4 book ai didi

dart - 声明必须是子类的Type变量-Dart

转载 作者:行者123 更新时间:2023-12-03 04:38:18 24 4
gpt4 key购买 nike

Kotlin代码:

Class<? extends Model> someType();
我想在Dart中做等效的事情,在其中我可以 声明一个变量,该变量存储必须从Model类扩展的类。
到目前为止,我只知道如何通过以下方式声明一个将通用类存储在Dart变量中的变量:
Type someType; 
但是我希望“someType”只能是从Model类扩展的类型/类。

最佳答案

Dart Type对象不是通用的。只有一个Type类,无法对它们进行子类型比较。 Type对象对其他任何东西也毫无用处。
您可能根本不应该使用Type对象。
它们很少是您所需要的,因为它们在大多数情况下非常无用。如果您不使用dart:mirrors,我建议根本不使用Type对象。
那么,为什么要存储一个Type值呢?
有什么方法可以将其存储为类型变量?
说,您需要知道类型才能创建该类型的列表。 Type对象无法做到这一点,但是可以使用适当的泛型类型变量。
考虑有一个像

class MyType<T> {
const MyType();
/// Perform [action] with [T] as type argument.
R callWithType<R>(R Function<T>() action) => action<T>();

// Checks and casts.
bool isInstance(Object o) => o is T;
T cast(Object o) => o as T;
T safeCast(Object o) => o is T ? o : null;

// Subtyping checks.
bool operator >=(MyType other) => other is MyType<T>;
bool operator <=(MyType other) => other >= this;
bool operator <(MyType other) => other >= this && !(this >= other);
bool operator >(MyType other) => this >= other && !(other >= this);
bool operator ==(Object other) =>
other is MyType && this >= other && other >= this;
int get hashCode => T.hashCode;

// Whatever other operations you want.
}
然后,您可以使用这种“类型表示对象”代替 Type对象,并且实际上可以将其用于实际操作。然后,您还可以要求使用 MyType对象作为受限类型:
MyType<Model> modelType; // Only `MyType` objects for `Model`s
// or
void withType<T extends Model>(MyType<T> type, ...) ...
您仍然只能执行类型变量支持的操作。您不能创建 T的新实例或查找类的静态成员,这些成员只能在实际的类中使用。

关于dart - 声明必须是子类的Type变量-Dart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63714341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com