在Dart中,Object()构造函数声明为const,因此:
identical(const Object(), const Object()); //true
Run Code Online (Sandbox Code Playgroud)
我知道在Dart 2中关键字const是可选的,并且我认为上一条语句等效于:
identical(Object(), Object()); //false
Run Code Online (Sandbox Code Playgroud)
但实际上它似乎等效于:
identical(new Object(), new Object()); //false
Run Code Online (Sandbox Code Playgroud)
现在我的疑问是:
1)const关键字何时是可选的?
2)有什么方法可以确保没有const关键字的类的实例始终保持不变?这样我可以获得:
indentical(MyClass(), MyClass()); //true (is it possible?)
Run Code Online (Sandbox Code Playgroud)
Dart 2允许您在new任何地方省略。new现在,您曾经写过的任何地方都可以省略。
Dart 2还允许您省略const上下文所隐含的位置。这些职位是:
const对象内部创建,映射或列出文字(const [1, [2, 3]])。@Foo(Bar()))中创建const对象时const x = [1];)的初始化表达式中。case Foo(2):...)。语言需要在其他两个位置使用常量表达式,但由于某些原因它们不会自动变为常量:
const构造函数的类中的最终字段的初始化程序表达式不能将1设为const,因为我们希望保留将来使这些表达式不必为const的选项。2是因为它是一个非局部约束- 表达式周围没有任何表示它必须为const的表达式,因此太容易了,例如,const从构造函数中删除而不注意到它会更改字段初始值设定项的行为。
const在const 上下文中是可选的。基本上,当表达式必须为 const 以避免编译错误时,就会创建const 上下文。
const在下面的代码片段中,您可以看到一些可选的地方:
class A {
const A(o);
}
main(){
// parameters of const constructors have to be const
var a = const A(const A());
var a = const A(A());
// using const to create local variable
const b = const A();
const b = A();
// elements of const lists have to be const
var c = const [const A()];
var c = const [A()];
// elements of const maps have to be const
var d = const {'a': const A()};
var d = const {'a': A()};
}
// metadatas are const
@A(const A())
@A(A())
class B {}
Run Code Online (Sandbox Code Playgroud)
您可以在可选的 new/const和隐式创建中找到更多详细信息。
| 归档时间: |
|
| 查看次数: |
590 次 |
| 最近记录: |