繁体   English   中英

在 Dart 中使用“this”初始化最终变量

[英]Initialize a final variable with "this" in Dart

我有一个这样的课程:

class A extends B {
  final Property<bool> property = Property<bool>(this);
}

class Property<T> {
  Property(this.b);
  final B b;
}

但是我在this句话上犯了一个错误:

对“this”表达式的引用无效。

我相信我当时无法访问this ,可能是因为对象引用尚未准备好。

所以我尝试了其他形式的初始化该变量,例如:

class A extends B {
  final Property<bool> property;
  A() : property = Property<bool>(this);
}

但我得到了同样的错误。

唯一有效的是:

class A extends B {
  Property<bool> property;
  A() {
   property = Property<bool>(this);
  }
}

这需要我删除final变量声明,这是我不想做的。

如何在 Dart 中初始化需要引用对象本身的final变量?

您不能在任何初始化程序中引用this ,因为this本身尚未初始化,因此您将无法将Property<bool> property设置为 final。

如果您只是想防止从实例外部修改property值,您可以使用私有成员并提供一个 getter 来防止修改。 鉴于您的示例,这看起来像这样:

class A extends B {

  // Since there's no property setter, we've effectively disallowed
  // outside modification of property.
  Property<bool> get property => _property;
  Property<bool> _property;

  A() {
   property = Property<bool>(this);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM