【问题标题】:What is the "const" keyword used for in Dart?Dart 中使用的“const”关键字是什么?
【发布时间】:2012-11-14 16:15:19
【问题描述】:

有人可以向我解释如何/何时/为什么使用const 关键字,或者它只是“一种声明常量变量的方法”?如果是这样,这有什么区别:

int x = 5;

const int x = 5;

你们能举个例子吗?

【问题讨论】:

标签: dart


【解决方案1】:

const 表示编译时间常数。表达式值必须在编译时已知。 const 修改“值”。

来自news.dartlang.org

“const”在 Dart 中具有更复杂和微妙的含义。 const 修改。您可以在创建集合时使用它, 像 const [1, 2, 3],以及在构造对象时(而不是 new) 像 const Point(2, 3)。这里, const 表示对象的全部 深度状态可以完全在编译时确定,并且 对象将被冻结并完全不可变。

如果你使用

const x = 5 然后变量 x 可以在像

这样的 cosnt 集合中使用
const aConstCollection = const [x];

如果你不使用const,而只使用x = 5 那么

const aConstCollection = const [x]; 是非法的。

更多来自www.dartlang.org的例子

class SomeClass {
  static final someConstant = 123;
  static final aConstList = const [someConstant]; //NOT allowed
}

class SomeClass {
  static const someConstant = 123; // OK
  static final startTime = new DateTime.now(); // OK too
  static const aConstList = const [someConstant]; // also OK
}

【讨论】:

  • 为什么我不能在没有静态的情况下使用 const?我的 const 不需要静态类范围,那么为什么我不得不使用将其声明为静态?
  • @robbie 您的常量也不需要为每个实例重复。既然是不变的,就永远不会改变,何必浪费空间去复制呢?通过强制静态声明常量,它们只为类放入内存一次,而不是每次创建实例时。我相信这个解释适用于 C# 和 Dart。
  • Dart 中的常量值是“规范化的”,因此它们只有一个实例,因此“静态常量”是多余的:“常量”就足够了。 Seth Ladd's article on this 的最后一段实际上表明“const”是首选样式,不鼓励使用“static const”。
  • 那么finalconst有什么区别呢?
【解决方案2】:

以下是关于const 值的一些事实:

  • 该值必须在编译时已知。

    const x = 5; // OK
    
  • 在运行时计算的任何东西都不能是const

    const x = 5.toDouble(); // Not OK
    
  • const 值意味着它是非常恒定的,也就是说,它的每个成员都是递归恒定的。

    const x = [5.0, 5.0];          // OK
    const x = [5.0, 5.toDouble()]; // Not OK
    
  • 您可以创建const 构造函数。这意味着可以从类中创建 const 值。

    class MyConstClass {
      final int x;
      const MyConstClass(this.x);
    }
    
    const myValue = MyConstClass(5); // OK
    
  • const 值是规范实例。这意味着无论您声明多少个实例,都只有一个实例。

    main() {
      const a = MyConstClass(5);
      const b = MyConstClass(5);
      print(a == b); // true
    }
    
    class MyConstClass {
      final int x;
      const MyConstClass(this.x);
    }
    
  • 如果您的班级成员是const,您还必须将其标记为staticstatic 表示它属于该类。因为只有一个 const 值的实例,所以它不是 static 是没有意义的。

    class MyConstClass {
      static const x = 5;
    }
    

另见

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多