📜  Dart – 吸气剂和二传手

📅  最后修改于: 2021-09-02 05:18:15             🧑  作者: Mango

GettersSetters,也称为访问器和修改器,允许程序分别初始化和检索类字段的值。

  • 使用 get 关键字定义获取器或访问器。
  • Setter 或 mutator 是使用 set 关键字定义的。

默认的getter / setter与每个类相关联。但是,可以通过显式定义 setter/getter 来覆盖默认值。 getter 没有参数并返回一个值,setter 有一个参数但不返回值。

Syntax: Defining a getter
 
Return_type  get identifier  
{  
    // statements
}  
Syntax: Defining a setter
 
set identifier  
{  
   // statements
}

示例 1:

以下示例显示了如何在Dart类中使用 getter 和 setter:

Dart
// Dart Program in Dart to illustrate
// getters and setters #GFG
class Student { 
   String name; 
   int age; 
      
   String get stud_name { 
      return name; 
   } 
      
   void set stud_name(String name) { 
      this.name = name; 
   } 
     
   void set stud_age(int age) { 
      if(age<= 0) { 
        print("Age should be greater than 5"); 
      }  else { 
         this.age = age; 
      } 
   } 
     
   int get stud_age { 
      return age;     
   } 
}  
void main() { 
   Student s1 = new Student(); 
   s1.stud_name = 'Nitin'; 
   s1.stud_age = 0; 
   print(s1.stud_name); 
   print(s1.stud_age); 
}


Dart
// Dart program in Dart to illustrate
// getters and setters #GFG
void main() {
  var cat = new Cat();
    
  // Is cat hungry? true
  print("Is cat hungry? ${cat.isHungry}");
    
  // Is cat cuddly? false
  print("Is cat cuddly? ${cat.isCuddly}");  
    
  print("Feed cat.");
  cat.isHungry = false;   
    
  // Is cat hungry? false
  print("Is cat hungry? ${cat.isHungry}");
    
   // Is cat cuddly? true
  print("Is cat cuddly? ${cat.isCuddly}"); 
}
  
class Cat {
  bool _isHungry = true;
    
  bool get isCuddly => !_isHungry;
    
  bool get isHungry => _isHungry;
  bool set isHungry(bool hungry) => this._isHungry = hungry;
}


输出:

Age should be greater than 5  
Nitin
Null 

示例 2:

Dart

// Dart program in Dart to illustrate
// getters and setters #GFG
void main() {
  var cat = new Cat();
    
  // Is cat hungry? true
  print("Is cat hungry? ${cat.isHungry}");
    
  // Is cat cuddly? false
  print("Is cat cuddly? ${cat.isCuddly}");  
    
  print("Feed cat.");
  cat.isHungry = false;   
    
  // Is cat hungry? false
  print("Is cat hungry? ${cat.isHungry}");
    
   // Is cat cuddly? true
  print("Is cat cuddly? ${cat.isCuddly}"); 
}
  
class Cat {
  bool _isHungry = true;
    
  bool get isCuddly => !_isHungry;
    
  bool get isHungry => _isHungry;
  bool set isHungry(bool hungry) => this._isHungry = hungry;
}

输出: