Dart编程中的获取器和设置器
在任何编程语言中,对对象的读写访问都非常重要。获取器和设置器是我们想要访问对象的属性的读写权限时使用的确切方法。
语法
获取器通常看起来像这样 -
returnType get fieldName {
// return the value
}returnType是我们正在返回的数据类型。get 关键字告诉我们和编译器这是一个获取器,最后我们有fieldName,我们试图获取其值。
设置器 通常看起来像这样 −
set fieldName {
// set the value
}set是关键字,告诉我们和编译器这是一个设置器方法。在set关键字之后,我们有fieldName,我们试图在以下代码块中设置其值。
现在,让我们创建一个名为Employee的类,在其中我们将有不同的字段来应用我们的获取器和设置器方法。
示例
考虑下面显示的示例 −
class Employee {
var empName = "mukul";
var empAge = 24;
var empSalary = 500;
String get employeeName {
return empName;
}
void set employeeName(String name) {
this.empName = name;
}
void set employeeAge(int age) {
if(age<= 18) {
print("Employee Age should be greater than 18 Years.");
} else {
this.empAge = age;
}
}
int get employeeAge {
return empAge;
}
void set employeeSalary(int salary) {
if(salary<= 0) {
print("Salary cannot be less than 0");
} else {
this.empSalary = salary;
}
}
int get employeeSalary {
return empSalary;
}
}
void main() {
Employee emp = new Employee();
emp.employeeName = 'Rahul';
emp.employeeAge = 25;
emp.employeeSalary = 2000;
print("Employee's Name is : ${emp.employeeName}");
print("Employee's Age is : ${emp.employeeAge}");
print("Employee's Salary is : ${emp.employeeSalary}");
}在上面的示例中,我们有一个 Employee 类,当我们在主函数内创建 Employee 类的对象时,然后使用不同的 getter 和 setter 方法来访问和写入对象的字段。
输出
Employee's Name is : Rahul Employee's Age is : 25 Employee's Salary is : 2000
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP