Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 颤振/飞镖获取功能arg类型,不带后视镜_Generics_Flutter_Dart - Fatal编程技术网

Generics 颤振/飞镖获取功能arg类型,不带后视镜

Generics 颤振/飞镖获取功能arg类型,不带后视镜,generics,flutter,dart,Generics,Flutter,Dart,所以我需要确定回调函数arg的类型 下面是一个测试,它演示了缺少可用的类型信息 void main() { Tester().test(); } class A {} class B extends A {} class Tester { void test() { // pass a function that takes B as an arg on((B arg) {}); } void on<T extends A>(Function(

所以我需要确定回调函数arg的类型

下面是一个测试,它演示了缺少可用的类型信息

void main() {
  Tester().test();
}

class A {}

class B extends A {}

class Tester {
  void test() {
    // pass a function that takes B as an arg
    on((B arg) {});
  }

  void on<T extends A>(Function(T value) listener) {
    Type type = T.runtimeType;
    if (type is B) {
      print("It worked");
    } else {
      print("Doh, type is $type");
      print("${listener.runtimeType}");
    }
  }
}
void main(){
Tester().test();
}
A类{}
类B扩展了{}
类测试员{
无效测试(){
//传递一个将B作为参数的函数
关于((B arg){});
}
(函数(T值)侦听器)上的void{
Type Type=T.runtimeType;
if(类型为B){
打印(“它起作用”);
}否则{
打印(“Doh,类型为$type”);
打印(${listener.runtimeType});
}
}
}
这是输出

I/颤振(26001):Doh,类型为_类型

I/颤振(26001):(B)=>Null


因此,这里有一个可行的解决方案:)

void main(){
Tester().test();
}
A类{}
类B扩展了{}
类C扩展了{}
类D{}
第一类{}
类测试员{
无效测试(){
on2((B arg){},B());
on2((A arg){},B());
on2((C-arg){},B());
on2((C arg){},C());
//dart中的类型检查并不会阻止使用D(它应该),但我们对on2方法进行了运行时检查
on2((D arg){},C());
}
void on2(函数(O值)侦听器,E emit){
var t1=I();
var t2=I();
if(t1.runtimeType==t2.runtimeType){
打印(“$t1=$t2”);
}
//catch函数的类型不扩展
if(t1.runtimeType.toString().toLowerCase()包含(“null”)){
打印(“无效类型$t1”);
}
}
}
输出

I/颤振(26219):I的实例==I的实例

I/颤振(26219):I的实例==I的实例

I/flatter(26219):无效的“I”类型实例


这个解决方案是不可靠的,有时类型是基类型。
void main() {
  Tester().test();
}

class A {}

class B extends A {}

class C extends A {}

class D {}

class I<T> {}

class Tester {
  void test() {
    on2((B arg) {}, B());
    on2((A arg) {}, B());
    on2((C arg) {}, B());
    on2((C arg) {}, C());

    // Type checking in dart doesn't prevent using D (it should), but we have a runtime check on the on2 method
    on2((D arg) {}, C());
  }

  void on2<O extends A, E extends A>(Function(O value) listener, E emit) {
    var t1 = I<O>();
    var t2 = I<E>();
    if (t1.runtimeType == t2.runtimeType) {
      print("$t1 == $t2");
    }

    // catch function with type that doesn't extend A
    if (t1.runtimeType.toString().toLowerCase().contains("null")) {
      print("INvalid type $t1");
    }
  }
}