代码之家  ›  专栏  ›  技术社区  ›  MistyD Harish Kumar Kailas

Dart:如何检查变量类型是否为字符串

  •  0
  • MistyD Harish Kumar Kailas  · 技术社区  · 7 年前

    我有这个密码。该类是泛型的,当我通过传递字符串类型实例化它时。变量变为字符串类型。但是声明

    if(_val is String){
    }
    

    似乎不是真的。知道为什么吗?

        class foo<T>{
        T _val;
        QVar()
        {
             //Read the value from preferences
             if(_val is String){
                ... //Does not come in here!!
             }
        }
      }
    
     a   = new foo<String>();
    
    1 回复  |  直到 7 年前
        1
  •  31
  •   ethane    7 年前

    而不是

    if(T is String)
    

    if(_val is String)
    

    is T refers to a type but is being used as a value .

    请注意,因为您有一个类型防护装置(即。 if(_val is String) _val 只可能是 String if -街区。

    as https://www.dartlang.org/guides/language/language-tour#type-test-operators .

        2
  •  5
  •   MendelG    5 年前

    .runtimeType 要获取类型,请执行以下操作:

    void main() {
    
    var data_types = ["string", 123, 12.031, [], {} ];`
      
    for(var i=0; i<data_types.length; i++){
    
        print(data_types[i].runtimeType);
    
        if (data_types[i].runtimeType == String){
          print("-it's a String");
    
        }else if (data_types[i].runtimeType == int){
          print("-it's a Int");
          
        }else if (data_types[i].runtimeType == [].runtimeType){
          print("-it's a List/Array");
    
        }else if (data_types[i].runtimeType == {}.runtimeType){
          print("-it's a Map/Object/Dict");
    
        }else {
          print("\n>> See this type is not their .\n");
        } 
    }}