2017-01-20 103 views
1

此代码不会对飞镖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')

回答

0

只是因为迭代通过.where()返回只能包含MethodMirror情况下,不允许演员。该类型从c.declarations.values传播,即DeclarationMirror。 虽然你可以将DeclarationMirror转换为MethodMirror,但从Iterable<DeclarationMirror>Iterable<MethodMirror>的剧组是无效的,因为它们之间不存在is-a关系。

看起来,当由dart2js构建到JS时,某些泛型类型被删除,这就是为什么它可以在DartPad中使用。

您可以创建一个新的List<MethodMirror>

import 'dart:mirrors'; 

class Thing { 
    Thing(); 
} 

void g(ClassMirror c) { 
    var constructors = new List<MethodMirror>.from(
     c.declarations.values.where((d) => d is MethodMirror && d.isConstructor)); 
    print(constructors); 
} 

void main() { 
    g(reflectClass(Thing)); 
} 

有一个悬而未决的问题,以使这更容易https://github.com/dart-lang/sdk/issues/27489

+0

感谢您的解决方案,和错误链接! –

相关问题