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

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

问题描述

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

有人可以给我解释一下冒号<$ c的语法含义吗? $ c>:?

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

推荐答案

Dart 中的此功能称为初始化程序列表。

它允许您初始化类的字段,进行 assertions 并调用超级构造函数。

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

这意味着它与构造函数主体不同。就像我说的那样,您只能初始化变量,并且只能访问 静态 成员。您不能调用任何(非静态)方法。

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天全站免登陆