【问题标题】:Using Setters with Constructors in Dart在 Dart 中使用带有构造函数的 Setter
【发布时间】:2021-01-05 22:25:46
【问题描述】:

如何在 Dart 的默认构造函数中使用私有实例变量的 setter?

给定示例类:

class A {
  String name;
  int _age;

  int get age => _age;

  set age(age) {
    _age = age ?? 0;
  }

  A(this.name, this._age);
}

如何使用这个构造函数来执行set age() 函数?除了使用factory 之外,还有其他方法吗?我想做这样的事情

A(this.name, newAge): age = newAge;

但我得到一个错误,迫使我只能从构造函数中设置实例变量,这让我只是复制了 setter:

A(this.name, newAge): _age = newAge ?? 0;

我是否遗漏了什么,或者这对飞镖来说是不可能的?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    构造函数的初始化列表只能用于初始化成员(或调用基类构造函数)。 (另外,当初始化列表执行时,this 还无效,所以你不能访问任何成员。)

    如果你想做其他类型的初始化工作,你可以在构造函数 body 中做,此时对象被认为是充分构造的,this 有效:

    A(this.name, int newAge) {
      age = newAge;
    }
    

    另见:

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 2019-12-27
      • 2013-04-16
      • 2018-12-03
      • 2020-11-17
      相关资源
      最近更新 更多