簡體   English   中英

在 Dart 中使用“this”關鍵字是什么意思?

[英]What does mean of using the "this" keyword in Dart?

如果這聽起來是一個非常愚蠢的問題,我很抱歉,但它確實一直困擾着我。

什么是“這個”。 我看到了嗎? 每當我在 flutter 中看到文檔時,我都會看到它在文檔中的以下內容中使用:

this.initialRoute,
this.onGenerateRoute,
this.onGenerateInitialRoutes,
this.onUnknownRoute,
this.navigatorObservers

我也很樂意閱讀有關它的任何鏈接或文檔。

基本上, this關鍵字用於表示當前實例。 看看下面的例子。

void main() {
  
  Person mike = Person(21);
  
  print(mike.height);
  
}

class Person {
  
  double height;
  
  Person(double height) {
    height = height;

  }
}

當我們運行這個 dart 代碼時,它輸出null作為高度。 因為我們在Person構造函數里面使用了height = height ,但是代碼不知道哪個height是 class 屬性。

因此,我們可以使用this關鍵字來表示當前實例,這將有助於代碼理解哪個height屬於該類。 所以,我們可以如下使用它,我們將得到正確的輸出。

void main() {
  
  Person mike = Person(21);
  
  print(mike.height);
  
}

class Person {
  
  double height;
  
  Person(double height) {
    this.height = height;

  }
}

“this”關鍵字指的是當前實例。 您只需要在出現名稱沖突時使用它。 否則,Dart 樣式會忽略 this。

class Car {
  String engine;

  void newEngine({String engine}) {
    if (engine!= null) {
      this.engine= engine;
    }
  }
}

所以你可以在構造函數或類中的某些函數中與你的參數名稱保持一致。

class Car {
  String engine;

  void updateEngine({String someWeirdName}) {
    engine = someWeirdName;
  }
}

如果您沒有名稱沖突,則不需要使用它。

在 Python 和 Swift 等其他語言中,“self”這個詞會和“this”做同樣的事情。

這個關鍵字的使用

The this keyword is used to point the current class object.

It can be used to refer to the present class variables.

We can instantiate or invoke the current class constructor using this keyword.

We can pass this keyword as a parameter in the constructor call.

We can pass this keyword as a parameter in the method call.

It removes the ambiguity or naming conflict in the constructor or method of our instance/object.

It can be used to return the current class instance.

this 關鍵字表示指向當前類對象的隱式對象。 它指的是方法或構造函數中類的當前實例。 this關鍵字主要用於消除類屬性和同名參數之間的歧義。 當類屬性和參數名稱相同時,使用 this 關鍵字通過在類屬性前加上 this 關鍵字來避免歧義。 this關鍵字可用於從實例方法或構造函數中引用當前對象的任何成員

此關鍵字的用途

  • 可以用來引用當前類的實例變量
  • 它可用於創建或啟動當前類構造函數
  • 它可以作為方法調用中的參數傳遞
  • 它可以在構造函數調用中作為參數傳遞
  • 它可用於制作當前類方法
  • 可以用來返回當前類的Instance

示例:以下示例顯示了此關鍵字的使用

// Dart program to illustrate 
// this keyword  
void main() 
{ 
  Student s1 = new Student('S001'); 
} 
  
class Student 
{ 
  // defining local st_id variable 
  var st_id; 
  Student(var st_id) 
  { 
    // using this keyword 
    this.st_id = st_id; 
    print("GFG - Dart THIS Example"); 
    print("The Student ID is : ${st_id}"); 
  } 
}

有關更多信息,請參閱: https : //www.geeksforgeeks.org/dart-this-keyword/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM