此代码不会对飞镖VM(1.22.0-dev.9.0)工作,但确实在DartPad工作(未知版本):为什么Iterable <DeclarationMirror>不能转换为Iterable <MethodMirror>?
import 'dart:mirrors';
class Thing {
Thing();
}
void g(ClassMirror c) {
var constructors = c.declarations.values
.where((d) => d is MethodMirror && d.isConstructor) as Iterable<MethodMirror>;
print(constructors);
}
void main() {
g(reflectClass(Thing));
}
结果:
Unhandled exception:
type 'WhereIterable<DeclarationMirror>' is not a subtype of type 'Iterable<MethodMirror>' in type cast where
WhereIterable is from dart:_internal
DeclarationMirror is from dart:mirrors
Iterable is from dart:core
MethodMirror is from dart:mirrors
#0 Object._as (dart:core-patch/object_patch.dart:76)
#1 g (file:///google/src/cloud/srawlins/strong/google3/b.dart:9:55)
#2 main (file:///google/src/cloud/srawlins/strong/google3/b.dart:14:3)
#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
(但在DartPad结果(MethodMirror on 'Thing')
)
需要注意的是,如果我的手工工艺实现对方,做同样的事情了一些类,它的工作原理:
abstract class DM {
bool get t;
}
abstract class MM implements DM {
MM();
bool get t;
}
class _MM implements MM {
bool get t => true;
}
void f(Map<dynamic, DM> dms) {
var mms = dms.values.where((dm) => dm is MM && dm.t) as Iterable<MM>;
print(mms);
}
void main() {
f({1: new _MM()});
}
这很好地打印:(Instance of '_MM')
感谢您的解决方案,和错误链接! –