冒号:在 Dart 构造函数语法中 [英] Colon : in Dart constructor syntax

查看:57
本文介绍了冒号:在 Dart 构造函数语法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class X extends Y {
  X(int a, int b) : super(a,b);
}

谁能给我解释一下冒号:的语法含义?

Can someone give me an explanation about the syntax meaning of the colon :?

推荐答案

Dart 中的此功能称为初始化列表".
它允许您初始化类的字段,进行断言并调用超级构造函数.

This feature in Dart is called "initializer list".
It allows you to initialize fields of your class, make assertions and call the super constructor.

这意味着它与构造函数体不同.正如我所说,您只能初始化变量并且只能访问static成员.您不能调用任何(非静态)方法.

This means that it is not the same as the constructor body. As I said, you can only initialize variables and only access static members. You cannot call any (non-static) methods.

好处是您还可以初始化 final 变量,而您在构造函数体中不能这样做.您还可以访问所有传递给构造函数的参数,而在直接在括号中初始化参数时,您没有这些参数.
此外,您可以在赋值左侧使用与引用参数的右侧参数同名的类字段.Dart 将自动使用左侧的 class 字段.
下面是一个例子:

The benefit is that you can also initialize final variables, which you cannot do in the constructor body. You also have access to all parameters that are passed to the constructor, which you do not have when initializing the parameters directly in the parentheses.
Additionally, you can use class fields on the left-hand of an assignment with the same name as a parameter on the right-hand side that refers to a parameter. Dart will automatically use the class field on the left-hand side.
Here is an example:

class X {
  final int number;

  X(number) : number = number ?? 0;
}

上面的代码将名为 number 的参数分配给 final 字段 this.number 如果它是非-null 否则分配 0.这意味着赋值的左侧number 实际上是指this.number.现在,你甚至可以做出一个永远不会失败的断言(因此是多余的,但我想解释一下一切是如何协同工作的):

The code above assigns the parameter named number to the final field this.number if it is non-null and otherwise it assigns 0. This means that the left-hand number of the assignment actually refers to this.number. Now, you can even make an assertion that will never fail (and is redundant because of that, but I want to explain how everything works together):

class X {
  final int number;

  X(number): number = number ?? 0, assert(number != null);
}

了解详情.

这篇关于冒号:在 Dart 构造函数语法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆