【问题标题】:How to count the number of instances of a Class in Dart?如何计算 Dart 中类的实例数?
【发布时间】:2022-11-26 14:35:11
【问题描述】:

在 Java 中,我们可以使用 instance initialization block 来跟踪任何类对象的计数。

那么,在 dart 中,我们如何为 const Constructor 的班级做到这一点?

我知道对于非常量构造函数,我们可以通过创建 static variable 然后在构造函数主体中递增其值来实现。

但是正如我们所知,const Constructor 不能有主体,那么如何跟踪为特定类创建的实例数?

【问题讨论】:

标签: dart


【解决方案1】:

使用 const 构造函数创建的类只能有一个实例。一个实例在编译期间实例化,所有const 对构造函数的调用都会返回它。

如果您想计算在非const 上下文中使用 const 构造函数的次数,这是不可能的,因为有可能在编译期间执行的代码不会导致运行时副作用。

考虑为此目的使用工厂构造函数,如下所示:

class MyClass {
  static var _instances = 0;

  const MyClass();

  factory MyClass.tracked() {
    ++_instances;
    return const MyClass();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 2014-10-24
    • 2011-08-04
    • 2018-10-06
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多