用"this"初始化最终变量.在达特 [英] Initialize a final variable with "this" in Dart

查看:88
本文介绍了用"this"初始化最终变量.在达特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的班级:

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

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

但是我在this上收到一条错误消息:

But I get an error on this saying:

对"this"表达式的引用无效.

Invalid reference to 'this' expression.

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

I believe I can't access this at that moment, probably because the object reference is not ready yet.

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

So I tried other forms of initializing that variable like:

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

但是我遇到了同样的错误.

But I get the same error.

唯一可行的是:

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

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

Which needs me to remove the final variable declaration, which is something I don't want to.

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

How can I initialize a final variable in Dart that needs a reference to the object itself?

推荐答案

您无法在任何初始化器中引用this,因为this本身尚未初始化,因此您将无法设置Property<bool> property是最终决定.

You can't reference this in any initializers as this hasn't yet been initialized itself, so you won't be able to set Property<bool> property to be final.

如果您只是想从实例外部阻止对property值的修改,则可以使用private成员并提供一个getter来防止修改.以您的示例为例,它看起来像这样:

If you're just trying to prevent modification of the value of property from outside the instance, you can use a private member and provide a getter to prevent modification. Given your example, that would look something like this:

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);
  }
}

这篇关于用"this"初始化最终变量.在达特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆