美文网首页
2021-02-24flutter类型转换 is 和as

2021-02-24flutter类型转换 is 和as

作者: 我是小胡胡123 | 来源:发表于2021-02-24 20:04 被阅读0次

is 、as 属于Type test operators。

is 判断是否是某个类型,返回true或者false。
如果a 是b的实现类,那么a is b 就返回true。

as 是类型转换,其相当于 :先检测 其是不是,然后再调用的一种简写。
但是还不是完全一致,当不是的时候,as 会抛出exception。

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}

可以简写为:

(emp as persion).firstName='Bob';

如果emp 不是persion,name就会抛出exception。

测试代码

void test<T>(T resultInfo) {
  Map info={};
  try {
    info = (resultInfo as Map<dynamic, dynamic>)['info'];
  } catch (e) {
    print(e);
  }
  info['picUrl'] = 'http://newpic';
  print(info);
}

void main() {
  Map info = {"postid": "123", "picUrl": "http://111.pic"};
  Map resultInfo = {"info": info};
  test(resultInfo);//resultInfo被修改
  print(resultInfo);//修改有效
  test(['123', '323']);
}


运行结果

{postid: 123, picUrl: http://newpic}
{info: {postid: 123, picUrl: http://newpic}}
TypeError: Instance of 'JSArray<String>': type 'JSArray<String>' is not a subtype of type 'Map<dynamic, dynamic>'
{picUrl: http://newpic}

相关文章

网友评论

      本文标题:2021-02-24flutter类型转换 is 和as

      本文链接:https://www.haomeiwen.com/subject/wcqefltx.html