Dart 入门教程(三),运算符篇

这是 Dart 入门第三篇文章,前两篇分享 Dart 的变量、函数,本文分享运算符,Dart 有很多有意思,并且有用的运算符。我把重要的两种运算符放在文章前面,其他的基本运算符很简单,放在文章后面。

Dart 入门教程(一),变量、集合篇

Dart 入门教程(二),函数篇

Dart 入门教程(三),运算符篇

Dart 入门教程(四),类的使用

Dart 入门教程(五),同步和异步

null 合并运算符

?? 运算符在 Dart 语言中被称为 null 合并运算符,它的作用是在左操作数为 null 时返回右操作数的值。这个运算符在 Dart 中用的非常多。

  int a;
  int b = 42;
  int c = a ?? b;
  print(c); // 输出:42

也可以在对象中使用

  class Person {
    String name;
    int age;

    Person({this.name, this.age});
  }

  void main() {
    Person person1 = Person(name: 'Alice', age: null);
    int age = person1.age ?? 18;
    print(age); // 输出:18
  }

甚至还可以链式嵌套使用

  int a;
  int b;
  int c = 42;
  int result = a ?? b ?? c;
  print(result); // 输出:42

级联运算符

Dart 中的级联运算符(..)允许您在同一个对象上连续调用多个方法或访问多个属性,而不需要重复引用对象。这有助于简化代码并提高可读性。这个运算符在项目开发中也经常用到,并且挺好用的。

  class Person {
    String name;
    int age;

    void setName(String newName) {
      name = newName;
    }

    void setAge(int newAge) {
      age = newAge;
    }

    void printInfo() {
      print('Name: $name, Age: $age');
    }
  }

  void main() {
    Person person = Person()
      ..setName('Alice')
      ..setAge(30)
      ..printInfo();
  }

上面是使用级联运算符的用法,如果不使用,则如下

	Person person = Person();
  person.setName('Alice');
  person.setAge(30);
  person.printInfo();

算术运算符

+, -, *, /, ~/, %)像这些运算符都比较简单,而且用法和大部分语言差不多。

  void main() {
    int a = 10;
    int b = 3;

    print(a + b); // 输出:13
    print(a - b); // 输出:7
    print(a * b); // 输出:30
    print(a / b); // 输出:3.3333333333333335
    print(a ~/ b); // 输出:3
    print(a % b); // 输出:1
  }

条件表达式/三元运算符

  void main() {
    int a = 10;
    int b = 3;

    int max = a > b ? a : b;
    print(max); // 输出:10
  }

这是 Dart 入门学习第三篇。虽然函数才是 Dart 的一等公民,但类也很重要,所以接下来是关于类的使用。

Dart 入门教程(一),变量、集合篇

Dart 入门教程(二),函数篇

Dart 入门教程(三),运算符篇

Dart 入门教程(四),类的使用

Dart 入门教程(五),同步和异步

本文由老郭种树原创,转载请注明:https://guozh.net/dart-getting-started-tutorial-operators/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注