【问题标题】:What's the difference between a normal method and a setter method in Dart?Dart 中的普通方法和 setter 方法有什么区别?
【发布时间】:2022-01-08 19:05:48
【问题描述】:

我昨天刚开始学习 Dart。我想知道 Dart 中的普通方法和 setter 方法有什么区别?例如,我有以下演示代码。

class Person {
  String? firstName;
  String? lastName;

  // Normal method
  fullName(String? name) {
    var names = name!.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
}

main() {
  Person p = Person();
  p.fullName('John Smith');
  print("${p.firstName} ${p.lastName}");
}

还有:

class Person {
  String? firstName;
  String? lastName;

  // Setter
  set fullName(String? name) {
    var names = name!.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
}

main() {
  Person p = Person();
  p.fullName = 'John Smith';
  print("${p.firstName} ${p.lastName}");
}

区别似乎只是调用语法。除此之外,还有其他区别吗?

【问题讨论】:

  • 它可以与get配对。虽然也许这也是“只是语法”..
  • 使用setter,你只能接受一个位置参数,它只能返回void

标签: dart methods setter


【解决方案1】:

这主要归结为约定。

通常你不会想要一个没有 getter 的 setter。 (尽管没有 setter 的 getter 很好……而且很常见。)

在你的情况下,我会使用一个 setter - 并且只需添加一个 getter!

(虽然我会在 setter 中添加更多检查以确保不会有人通过 "A string with more spaces!")。

【讨论】:

    【解决方案2】:

    使用 setter,您将不需要括号来将值作为参数传递。相反,您将使用等号。而setter的另一点是getter的返回类型应该和setter的param类型一致。

    class User{
     late _age; 
    
     get age(){
      return _age;
     }
    
     set age(int age){
      _age = age;
     }
    }
    
    void main(){
     var user = User();
     user.age = 4; 
    
     print("age is ${user.age}");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 2013-04-29
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多