簡體   English   中英

如何在 dart 中獲取通用 Object 的主要類型和子類型,例如 Type1<type2> , 我只想要 Type1 和 Type2 分開</type2>

[英]How do I get the main type and subtype of a Generic Object in dart, For ex Type1<Type2>, I just want the Type1 separatly and Type2 separatly

我想要Flutter中一個泛型類型的主類型和子類型。 因此,例如,如果我有List<int> ,我希望Listint都分開。 如果我這樣做<int>[1,2,3].runtimeType ,它會給我List<int> 但是,如果我只對該信息的 List 或 int 部分感興趣怎么辦。

我正在創建一個類型比較器來對我的數據進行排序

int typeSortHelper(Type type1, Type type2){
  if(type1 == type2){
    return 0;
  }

  if(type2 is List){
    type2 = List;
  }

  switch(type1){
    case int: return 1;
    case double:{
      int r;
      if(type2 == int){
        r= -1;
      }else{
        r= 1;
      }
      return r;
    }
    case String:{
      int r;
      if(type2 == int || type2 == double){
        r= -1;
      }else{
        r= 1;
      }
      return r;
    }
    case List:{
      int r;
      if(type2 == int || type2 == double || type2 == String){
        r= -1;
      }else{
        r= 1;
      }
      return r;
    }
    case Map:{
      int r;
      if(type2 == int || type2 == double || type2 == String || type2 == List){
        r= -1;
      }else{
        r= 1;
      }
      return r;
    }
  }

}

所以當我這樣打電話時:

r1 = typeSortHelper([1,2,3].runtimeType, 2.runtimeType);

它應該給我-1,而不是給我null。

可悲的是,你還不能這樣做。

因此,您在 2019 年(Dart 2.5)的實現將如下所示:

switch(smth.runtimeType){
  case int: return processInt(smth);
  case Uint8List: return process Uint8List(smth):
  default: if(smth is Map<String, dynamic>){
    processMapStringDynamic(smth);  
  } else if(smth is List<int>){
    processListInt(smth);
  } else throw('unimplemented for ${smth.runtimeType}');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM