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

Dart中this关键字与$运算符结合出现异常输出的问题咨询

Dart字符串插值中this.x的问题解析

问题原因

Dart的字符串插值有明确语法规则:如果插值的是单个变量名(比如$x),直接书写即可;但涉及属性访问、方法调用这类复杂表达式时,必须用大括号{}把整个表达式包裹起来。你写$this.x时,Dart只会将$this识别为插值对象,把实例转换成默认字符串(即Instance of 'Example'),后面的.x会被当作普通文本拼接,所以才会出现不符合预期的输出。

解决办法

将$this.x修改为${this.x},用大括号包裹整个this.x表达式,让Dart正确识别这是访问实例的x属性,而非先转换this再拼接文本。

代码对比

出错的代码

class Example {
  int x = 1;

  void method1() {
    int x = 5;
    print("I am $x"); // 正常输出: I am 5
    print("I am $this.x"); // 错误输出: I am Instance of 'Example'.x
  }
}

void main() {
  Example().method1();
}

修正后的代码

class Example {
  int x = 1;

  void method1() {
    int x = 5;
    print("I am $x"); // 输出: I am 5
    print("I am ${this.x}"); // 输出: I am 1
  }
}

void main() {
  Example().method1();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:59:55