【问题标题】:Is there any case in dart where using 'new' keyword is necessity?飞镖中是否有必要使用“新”关键字?
【发布时间】:2022-01-21 04:39:14
【问题描述】:

我最近在学习了核心 java 之后跳到了飞镖。使用类似的 java 概念,我尝试使用 new 关键字创建类“Product”的对象,dart 警告“不必要的新关键字”。

void main() {
 Product oil = new Product('sunflower', 2, 300);
 final noodles = Product('waiwai', 20, 20); //name, qty, price
}

所以,我的问题是,在 dart 中省略 new 对我们有什么好处?如果仍然有任何情况下使用 new 关键字是绝对必要的,因为它没有被完全省略?

【问题讨论】:

  • stackoverflow.com/questions/50091389/…这是回答你的问题吗?
  • 这能回答你的问题吗? Do you need to use the "new" keyword in Dart?
  • @Bhavin 在某种程度上,是的,但我还想知道的是,如果省略 new 也可以,为什么它没有完全删除?另外,我可以看到一条评论说“Dart 团队现在不得不撤回一点,在某些情况下仍然需要 new 或 const (我不记得示例或规则)。”所以,我也希望通过例子来学习。
  • 它没有被删除,因为这会破坏现有的 Dart 代码。 new 永远不需要。 (const 是另一回事。)
  • 从 dart 2.15 (medium.com/dartlang/dart-2-15-7e7a598e508a) 开始有一个称为构造函数撕裂的功能,它允许您使用 Product.new 引用类的默认构造函数。这本质上是一个名为new 的方法,而不是new 关键字,但无论如何,构造函数分离是唯一应该使用new 的地方。

标签: flutter dart new-operator


【解决方案1】:

省略new的好处是不用写多余的字母,可以节省时间。 Dart 编译器可以将创建的对象与另一个对象区分开来。

但是在 Dart 中有一个地方你仍然需要 new - 撕下构造函数。例如:

void main(List<String> args) {
  boxPutter(Box.new); // new style with tear-offs constructor
  boxPutter((something) => Box(something)); // old style
}

class Box {
  Box(this.staff);
  final int staff;

  @override
  String toString() => 'Box($staff)';
}

void boxPutter(Box Function(int something) constructor) {
  final staffGenerator = 10;
  print(constructor(staffGenerator));
}

【讨论】:

    猜你喜欢
    • 2019-05-09
    • 1970-01-01
    • 2014-02-17
    • 2021-10-16
    • 1970-01-01
    • 2014-07-27
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多