就像标题所说的那样:如果你有一个存储在变量中的Type,就我所知,没有办法将你的实际对象与这个类型的变量进行比较。我可以完成我正在尝试用镜子做的事情,但我不想,如果可能的话。
void example() {
Type myType = String;
String myExample = "Example";
//Syntax error here: The name 'myType' is not a type and cannot be used in an 'is' expression
if (myExample is myType) {
}
}
答案 0 :(得分:5)
您通常无法使用Type对象测试值是否为类型。
类型对象是反射类型,而不是真实类型。它们表示真实类型,但您不能在需要类型的代码中使用它们:作为类型断言,作为泛型类型参数或使用is / as运算符。您必须在这些位置使用类型的名称,而不是恰好包含Type对象的普通变量的名称。
使用镜子的聪明的东西可能会到达那里,但在大多数情况下它可能有点过分(我知道你不想要它)。
您可能可以做的是不传递原始Type对象。您可以改为创建自己的类型抽象,例如:
class MyType<T> {
const MyType();
Type get type => T;
bool isA(Object object) => object is T;
}
然后,您可以使用它来表示类型,而不是类型对象,并执行以下操作:
void main(List<String> args) {
MyType myType = const MyType<String>();
String myExample = "Example";
if(myType.isA(myExample)) {
print('is');
} else {
print('is not');
}
}
这确实要求整个程序使用您的类型对象来传递类型,但它也可以让您对这些对象进行大量控制,因此您可以实现所需的功能。
答案 1 :(得分:1)
我试过
library x;
void main(List<String> args) {
Type myType = String;
String myExample = "Example";
if(myExample.runtimeType == myType) {
print('is');
} else {
print('is not');
}
}
它有效。 我在Dart中对这些代码的经验不多。也许这不是一种自动防故障方法。
答案 2 :(得分:1)
import 'package:reflection/reflection.dart';
void main() {
var childType = typeInfo(Child);
var baseType = typeInfo(Base);
if(childType.isA(baseType)) {
print("Child is Base");
}
if(baseType.isAssignableFrom(childType)) {
print("Base is assignable from Child");
}
}
class Base {
}
class Child extends Base {
}
Child is Base
Base is assignable for Child
P.S。
“反射”包与dart2js不兼容。它只适用于Dart语言。