使用“类型”的Dart类型检查 [英] Dart type check using "Type"
问题描述
如何使用Child类实例检查Super类的类型?我有以下例子,不想使用dart-mirror。
How to check type of Super class with Child class instance? I have below example and don't want to use dart-mirrors.
class SomeClass{
}
class SomeOtherClass extends SomeClass{
}
void main() {
var s1 = new SomeOtherClass();
someMethod(SomeClass, s1);
}
void someMethod(Type t, dynamic instance){
print(instance.runtimeType == t);
//print(instance.runtimeType is t); Does not work!
}
推荐答案
更新
只是今天,包可反映已发布,允许做这类似于镜像,但是变换器生成代码,以避免在生产中使用镜像。
Update
Just today the package reflectable was released which allows to do this like with mirrors, but a transformer generates code instead to avoid using mirrors in production.
import 'package:reflectable/reflectable.dart';
// Annotate with this class to enable reflection.
class Reflector extends Reflectable {
const Reflector()
: super(typeCapability); // Request the capability to invoke methods.
}
const reflector = const Reflector();
@reflector
class SomeClass{
}
@reflector
class SomeOtherClass extends SomeClass{
}
void someMethod(Type t, dynamic instance){
InstanceMirror instanceMirror = reflector.reflect(instance);
print(instanceMirror.type.isSubclassOf(reflector.reflectType(t)));
}
void main() {
var s1 = new SomeOtherClass();
someMethod(SomeClass, s1);
}
原始
在实施 https://github.com/gbracha/metaclasses 时,可能会直接受到支持。
Original
It might be directly supported when https://github.com/gbracha/metaclasses is implemented.
目前可以使用此解决方法:
Currently this workaround can be used:
class IsInstanceOf<E> {
bool check(t) => t is E;
}
void someMethod(Type t, dynamic instance){
print( new IsInstanceOf<t>().check(instance));
//print(instance.runtimeType is t); Does not work!
}
这样运行正常,返回正确的结果,但分析仪显示警告, code> t 不能用作类型。
This runs fine and returns the correct result but the analyzer shows a warning because t
can't be used as a type.
如果换行 SomeClass
在一个泛型类中它工作没有警告
If you wrap SomeClass
in a generic class it works without a warning
class SomeClass{
}
class SomeOtherClass extends SomeClass{
}
void main() {
var s1 = new SomeOtherClass();
someMethod(new IsInstanceOf<SomeClass>(), s1);
}
void someMethod(IsInstanceOf t, dynamic instance){
print(t.check(instance));
//print(instance.runtimeType is t); Does not work!
}
class IsInstanceOf<E> {
bool check(instance) => instance is E;
}
请尝试 DartPad
这篇关于使用“类型”的Dart类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!