Dart超级初始化程序构造函数与私有成员

huangapple go评论73阅读模式
英文:

Dart super-initializer constructor with private members

问题

I'm currently learning Dart and have just written a class which extends a Base and uses the "super.* syntax" to initialize it. The member variable of the base which gets initialized is private and therefore prefixed with an underscore.

class X {
  final int _i;
  X(this._i);
}

class Y extends X {
  Y(super.i);
}

For some reason though the compiler is happy with me omitting the underscore in the derived class. Why? Omitting it in the base generates a compiler error.

英文:

I'm currently learning Dart and have just written a class which extends a Base and uses the "super.* syntax" to initialize it. The member variable of the base which gets initialized is private and therefor prefixed with an underscore.

class X {
  final int _i;
  X(this._i);
}

class Y extends X {
  Y(super.i);
}

For some reason though the compiler is happy with me omitting the underscore in the derived class. Why? Omitting it in the base generates a compiler error.

答案1

得分: 2

Y(super.i) 并不使用 name i 以外的任何内容,仅用于文档说明。参数是位置参数,它会在不考虑名称的情况下转发到超类构造函数中的相同位置。你可以声明它为 Y(super.arglebargle),它将同样有效。

命名参数会使用它们的名称,因此只有在位置参数的情况下才能编写任何内容。

英文:

The Y(super.i) doesn't use the name i for anything other than documentation.
The parameter is positional, and it's forwarded to the same position in the superclass constructor without looking at the name at all. You could declare it Y(super.arglebargle) and it would work just the same.

Named parameters do use their names, so it's only for positional super-parameters that you can write anything.

huangapple
  • 本文由 发表于 2023年3月20日 23:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定