Flutter Dart中的类型继承检查仅基于类型实例
给定Dart(颤振)中的两个Flutter Dart中的类型继承检查仅基于类型实例,flutter,dart,Flutter,Dart,给定Dart(颤振)中的两个Type实例,是否有方法确定一种类型是继承还是实现另一种类型 final Type first=atypefromwhere; 最后一个类型第二个=来自其他地方的类型; //如何确定第一个是否从第二个继承? 似乎对此没有任何功能。您可以使用dart:mirrors: import 'dart:mirrors'; class A {} class B extends A {} void main() { final typeA = A().runtimeTy
Type
实例,是否有方法确定一种类型是继承还是实现另一种类型
final Type first=atypefromwhere;
最后一个类型第二个=来自其他地方的类型;
//如何确定第一个是否从第二个继承?
似乎对此没有任何功能。您可以使用dart:mirrors:
import 'dart:mirrors';
class A {}
class B extends A {}
void main() {
final typeA = A().runtimeType;
final typeB = B().runtimeType;
final classMirrorA = reflectClass(typeA);
final classMirrorB = reflectClass(typeB);
print(classMirrorA.isSubclassOf(classMirrorB)); // false
print(classMirrorB.isSubclassOf(classMirrorA)); // true
}
import 'package:reflectable/reflectable.dart';
import 'main.reflectable.dart';
@MyReflectable()
class A {}
@MyReflectable()
class B extends A {}
class MyReflectable extends Reflectable {
const MyReflectable()
: super(typeRelationsCapability, superclassQuantifyCapability);
}
const myReflectable = const MyReflectable();
void main() {
initializeReflectable();
final typeA = A().runtimeType;
final typeB = B().runtimeType;
final classMirrorA = myReflectable.reflectType(typeA);
final classMirrorB = myReflectable.reflectType(typeB);
print(classMirrorA.isSubtypeOf(classMirrorB)); // false
print(classMirrorB.isSubtypeOf(classMirrorA)); // true
}
要做到这一点,更复杂的方法是使用软件包(但由颤振支持)。这个软件包有很多局限性,使用起来不是很好。但它可以在构建阶段构建所需的反射
我制作了以下示例,与我之前的示例相同,但现在没有使用省道:镜像:
import 'dart:mirrors';
class A {}
class B extends A {}
void main() {
final typeA = A().runtimeType;
final typeB = B().runtimeType;
final classMirrorA = reflectClass(typeA);
final classMirrorB = reflectClass(typeB);
print(classMirrorA.isSubclassOf(classMirrorB)); // false
print(classMirrorB.isSubclassOf(classMirrorA)); // true
}
import 'package:reflectable/reflectable.dart';
import 'main.reflectable.dart';
@MyReflectable()
class A {}
@MyReflectable()
class B extends A {}
class MyReflectable extends Reflectable {
const MyReflectable()
: super(typeRelationsCapability, superclassQuantifyCapability);
}
const myReflectable = const MyReflectable();
void main() {
initializeReflectable();
final typeA = A().runtimeType;
final typeB = B().runtimeType;
final classMirrorA = myReflectable.reflectType(typeA);
final classMirrorB = myReflectable.reflectType(typeB);
print(classMirrorA.isSubtypeOf(classMirrorB)); // false
print(classMirrorB.isSubtypeOf(classMirrorA)); // true
}
要使用它,您需要将以下依赖项添加到pubspec.yaml中:
可反射:^2.1.0
生成运行程序:^1.6.0
生成运行程序核心:^3.0.0
并运行以下命令(如果反射的类位于bin中):
并非所有想要使用isSubtypeOf的类都需要使用“@MyReflectable()”指定自身和所有超类,以便预编译器可以检测到它
pub run build_runner build bin/
我很害怕,因为我使用的是不支持镜子的颤振。有点希望如此基本的东西不需要镜子。无论如何,谢谢。好吧,如果你想要一个关于颤振的有效解决方案,你应该在问题中详细说明它(你现在已经有了)。我有些东西适合你,我正在更新我的答案。:)谢谢虽然我不能实际使用它,但它显然是最好的可用资源。