简体   繁体   English

在 Dart 中混合初始化器和构造器主体

[英]Mixing Up an Initializer and a Constructor Body in Dart

I know that you can initialize final variables in a class with something like:我知道您可以使用以下内容初始化类中的final变量:

class A {
  final num x;
  final num y;
  final num d;

  A(this.x, this.y): 
    d = sqrt(pow(x, 2) + pow(y, 2));
}

And you can create regular variables inside a constructor like this:您可以在构造函数中创建常规变量,如下所示:

class A {
  String z;

  A(){
    z = 'hello';
  }
}

But how do you mix both?但是你如何混合两者呢? Is it possible?是否可以? What is the syntax?语法是什么?

Simply continue with the constructor right after the initializer, but, since you're going to use curly brackets ( {} ), you shouldn't use the semi-colon ( ; ):只需在初始化程序之后立即继续构造函数,但是,由于您将使用大括号 ( {} ),因此不应使用分号 ( ; ):

class A {
  final num x;
  final num y;
  final num d;
  String z;

  A(this.x, this.y) 
    : d = sqrt(pow(x, 2) + pow(y, 2))
  {
    z = 'hello';
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM