Dart:如何检查变量类型是否为String

时间:2019-01-22 05:23:17

标签: dart

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

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>();

2 个答案:

答案 0 :(得分:2)

使用 .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");
    } 
}}

答案 1 :(得分:1)

代替

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-

如果需要显式转换,可以看看Dart https://www.dartlang.org/guides/language/language-tour#type-test-operators中的as运算符。