为什么第二个短格式构造函数会给出必须初始化 name 和 age 而不是注释的 ctor 的错误?

why the second short form constructor gives the error that name and age must be initialized but not the commented ctor?

我是飞镖语言的初学者。 所以我创建了这个 class ..

class X{
  String name;
  int age;
  // X(this.name,this.age); 
  X(name,age);
}

在这段代码中,缩写形式的 ctor X(name,age) 给出了必须初始化姓名和年龄的错误,但是 ctor X(this.name,this.age) 没有给出这样的错误。

In ctor X(this.name,this.age) 编译器知道 name 和 age 肯定会被初始化.. 但是在 ctor X(name,age) 中为什么编译器不能那样做....(不是很明显 name 和 this.name 是同一件事)。

请详细说明....

在 Dart 中,如果您不指定任何类型,在这种情况下,语言将假设您指的是 dynamic

所以你的代码实际做的是:

class X{
  String name;
  int age;

  X(dynamic name, dynamic age);
}

然后问题就变成了我们没有将这些参数分配给 class 中的任何内容,因为构造函数中的 name 与 [=13] 不同 name =] 在 class 定义中。

分析器因此会抱怨 nameage 没有被提供一个值,因为这两个字段都是用 non-nullable 类型定义的,因此不能是 null(这是 Dart 中任何变量的默认值,无论其类型如何)。

this.namethis.age是以下代码的快捷方式:

class X{
  String name;
  int age;

  X(String name, int age) : name = name, age = age;
}

name = name 起作用是因为我们不允许在构造函数的初始化部分将参数设置为其他值。所以 Dart 可以假定第一个 name 必须表示 class 变量,而第二个 name 表示参数,因为参数是范围最接近的参数。