Dart 编程中的此关键字
Dart 中使用此关键字可以消除类属性和参数同名容易产生歧义的问题。此关键字本质上表示一个隐式对象,指向当前类对象。
每当我们想要消除类属性和参数之间的歧义时,我们通常使用此关键字作为类属性的前缀。
示例
下面给出两个类属性和参数同名的示例。
考虑如下所示的示例 −
void main() {
Employee emp = new Employee('001');
emp.empCode = '111';
}
class Employee {
String empCode;
Employee(String empCode) {
this.empCode = empCode;
print("The Employee Code is : ${empCode}");
}
}在上面的代码中,我们可以清楚地看到 Employee 类有一个名为 empCode 的属性,还有一个同名参数。因此,在随后的 Employee() 构造函数中,我们只需使用此关键字来消除同名造成的歧义。
输出
The Employee Code is : 001
示例
我们考虑另一个包含不同类和属性的示例。
考虑如下所示的示例 −
void main() {
Student studentOne = new Student('001');
studentOne.studentId = '99';
}
class Student {
// local studentId variable
var studentId;
Student(var studentId) {
// using this keyword
this.studentId = studentId;
print("The Student ID is : ${studentId}");
}
}输出
The Student ID is : 001
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP