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

Mis*_*tyD 3 dart

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

if(_val is String){
}
Run Code Online (Sandbox Code Playgroud)

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

这是完整的代码:

    class foo<T>{
    T _val;
    QVar()
    {
         //Read the value from preferences
         if(_val is String){
            ... //Does not come in here!!
         }
    }
  }

 a   = new foo<String>();
Run Code Online (Sandbox Code Playgroud)

eth*_*ane 6

代替

if(T is String)
Run Code Online (Sandbox Code Playgroud)

它应该是

if(_val is String)
Run Code Online (Sandbox Code Playgroud)

is运算符在运行时用作类型防护,它对标识符(变量)进行操作。在这种情况下,大多数情况下,编译器会告诉您一些类似的内容T refers to a type but is being used as a value

请注意,由于您具有类型保护(即if(_val is String)),因此编译器已经知道的类型_val只能String在您的if-block 内部。

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


小智 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");
    } 
}}
Run Code Online (Sandbox Code Playgroud)