跳到主要内容

dart类型转换 is as

管

管理员

flutter

2020年09月17日 9,286 次阅读
本页目录

参考java的向上转型和向下转型:https://wodecun.com/blog/8131.html
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 main(List<String> arguments) {
  //向上转型
  Test test2 = Test2();
//判断test2是否Test2类的实现
  print(test2 is Test2);

  //向下转型 (as强制类型转换)
  //方法1:
  if(test2 is Test2)
  {
    test2.cs(); //在这个if体中idea可以提示 cs() 外部不提示
  }
  //方法2
  // (test2 as Test2).cs();
  //或者拆分:
  Test2 test = test2 as Test2;
  test.cs();
  
  print(test.runtimeType); //输出:Test2

}
class Test {}
class Test2 extends Test {
  cs() {
    print('test2-cs');
  }
}

Related

相关文章

同分类文章 →
2026年10月31日 flutter

`auth()->id()` 到底返回谁?Sanctum 多态令牌与双会员系统的踩坑记录

## 引子先看一段看起来很正常的代码:```php$userId = auth('sanctum')-&gt;id();if ($userId) {    $res['isLiked'] = $this-&gt;likes()        -&gt;where('user_id', $userId

2026年07月28日 flutter

Dart 3 记录(Records)和密封类(Sealed classes)

Dart 3 引入了几个极其强大的语言特性,其中最耀眼、对我们日常开发改变最大的就是 记录(Records) 和 密封类(Sealed classes),它们配合 模式匹配(Pattern Matching),让 Dart 的表现力达到了现代编程语言(如 Swift、Kotlin、Rust

2026年06月29日 flutter

flutter的 Clean Architecture架构设计

Clean Architecture(清晰架构)是一种将应用程序分层的设计模式,强调关注点分离与依赖规则,通过将业务逻辑与框架、UI、数据源解耦,提升代码的可测试性、可维护性与可扩展性。在 Flutter/Dart 环境下,Clean Architecture 通

WeChat

扫码加我微信

微信二维码