20

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

int x = 5;

const int x = 5;

各位大佬能给我举个例子吗?

4

2 回答 2

22

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

来自news.dartlang.org

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

如果你使用

const x = 5然后变量 x 可以用于像

const aConstCollection = const [x];

如果你不使用const,就使用x = 5then

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
}
于 2012-11-27T05:17:06.323 回答
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;
    }
    

也可以看看

于 2020-07-04T07:46:27.267 回答