Dart中的构造方法和初始化方法列表有什么区别? [英] What is the difference between constructor and initializer list in Dart?

查看:1136
本文介绍了Dart中的构造方法和初始化方法列表有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个代码的输出相同,但是本质区别是什么?

The output of the following two codes are the same, but what is the essential difference?

Dart语言之旅-初始化程序列表

import 'dart:math';

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point(x, y)
      : x = x,
        y = y,
        distanceFromOrigin = sqrt(x * x + y * y);
}

main() {
  var p = new Point(3, 4);
  print(p.distanceFromOrigin);
}

我的代码

  Point(this.x, this.y)
      : distanceFromOrigin = sqrt(x * x + y * y);

两个输出都相同5。


  • 如何正确使用构造函数和初始化列表?

  • Dart 2
  • DartPad

最好的问候,

推荐答案

没有区别,结果相同,只是可以利用不同类型的构造函数。

There is no difference, the result will be the same except that you can take advantage of different type of constructors.

如果您不想公开Point中定义的变量,而又不想将其标记为私有,则初始化器将是一个不错的选择。

In the case you don't want to expose your variables defined in Point and your mark those as private, the initializer would be a good option.

    class Point {
      final num _x;
      final num _y;
      final num _distanceFromOrigin;

      Point(x, y)
          : _x = x,
            _y = y,
            _distanceFromOrigin = sqrt(x * x + y * y);
    }

也可以看看带有可选参数或工厂构造函数的构造函数。

Also take a look to the constructor with optional parameters or factory constructors.

这篇关于Dart中的构造方法和初始化方法列表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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