【问题标题】:Initialize a final variable with "this" in Dart在 Dart 中用“this”初始化最终变量
【发布时间】:2020-04-14 09:48:24
【问题描述】:

我有这样的课:

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 变量?

【问题讨论】:

    标签: dart final


    【解决方案1】:

    您不能在任何初始化程序中引用this,因为this 本身尚未初始化,因此您无法将Property&lt;bool&gt; property 设置为最终的。

    如果您只是想阻止从实例外部修改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);
      }
    }
    

    【讨论】:

    • 是的,只是这种样板正是我试图通过创建Property 来避免的,它是一个封装getter 和setter 并同时提供更改通知的类。跨度>
    • 是的,这完全可以理解。但是,这是您可以在不久的将来使用late fields 处理的事情,当语言默认变为不可为空时。在这种情况下,我认为以下代码是有效的:class A { late final Property&lt;bool&gt; property; A() { property = Property&lt;bool&gt;(this); } }
    • 哦,那太棒了!
    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2021-03-09
    相关资源
    最近更新 更多