You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中Student student;与Student student = new Student();的区别是什么

Dart 两种类实例声明写法的区别

第一种写法:Student student;

  • 非空安全版本(Dart 2.12 之前):仅声明了类型为Student的引用变量student,没有初始化赋值,变量默认值为null,此时直接调用student的属性或方法会触发空指针异常。
  • 空安全版本(Dart 2.12 及之后):默认无法通过编译,因为非可空类型变量要求在使用前完成初始化。如果要保留类似写法,需要额外加标记:
    • 加可空标记Student? student;:变量为可空类型,默认值为null
    • 加延迟初始化标记late Student student;:编译时不会要求立即赋值,但使用前必须完成赋值,否则运行时会抛出LateInitializationError异常。

第二种写法:Student student = new Student();

  • 同时完成了变量声明和初始化操作:通过new关键字调用Student类的无参构造函数,在内存中创建了Student类的实例对象,将实例的引用赋值给student变量。
  • Dart 2 版本后new关键字为可选项,写成Student student = Student();效果完全一致。
  • 空安全环境下可正常编译运行,调用student的属性和方法不会有空指针风险。

内容的提问来源于stack exchange,提问作者Kiumars Chalangi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:54:03