📜  Dart

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

Dart的Typedef 用于为函数创建用户定义的标识(别名),我们可以在程序代码中使用该标识代替函数。当我们使用 typedef 时,我们可以定义函数的参数。

Syntax: typedef function_name ( parameters );

在 typedef 的帮助下,我们还可以为函数分配一个变量。

Syntax:typedef variable_name = function_name;

分配变量后,如果我们必须调用它,那么我们将执行以下操作:

Syntax: variable_name( parameters );

通过这种方式,我们将能够以不同的方式使用单个函数:

示例 1:在Dart使用 typedef。

Dart
// Dart program to show the usage of typedef
 
// Defining alias name
typedef GeeksForGeeks(int a, int b);
 
// Defining Geek1 function
Geek1(int a, int b) {
  print("This is Geek1");
  print("$a and $b are lucky geek numbers !!");
}
 
// Defining Geek2 function
Geek2(int a, int b) {
  print("This is Geek2");
  print("$a + $b is equal to ${a + b}.");
}
 
// Main Function
void main()
{
  // Using alias name to define
  // number with Geek1 function
    GeeksForGeeks number = Geek1;
  // Calling number
  number(1,2);
   
  // Redefining number
  // with Geek2 function
  number = Geek2;
  // Calling number
  number(3,4);
}


Dart
// Dart program to show the usage of typedef
 
// Defining alias name
typedef GeeksForGeeks(int a, int b);
 
// Defining Geek1 function
Geek1(int a, int b) {
  print("This is Geek1");
  print("$a and $b are lucky geek numbers !!");
}
 
// Defining a function with a typedef variable
number(int a, int b, GeeksForGeeks geek) {
  print("Welcome to GeeksForGeeks");
  geek(a, b);
}
 
// Main Function
void main()
{
  // Calling number function
  number(21,23, Geek1);
}


输出:

This is Geek1
1 and 2 are lucky geek numbers !!
This is Geek2
3 + 4 is equal to 7.

注意:除此之外,typedef 还可以作为函数的参数。

示例 2:使用 typedef 作为函数的参数。

Dart

// Dart program to show the usage of typedef
 
// Defining alias name
typedef GeeksForGeeks(int a, int b);
 
// Defining Geek1 function
Geek1(int a, int b) {
  print("This is Geek1");
  print("$a and $b are lucky geek numbers !!");
}
 
// Defining a function with a typedef variable
number(int a, int b, GeeksForGeeks geek) {
  print("Welcome to GeeksForGeeks");
  geek(a, b);
}
 
// Main Function
void main()
{
  // Calling number function
  number(21,23, Geek1);
}

输出:

Welcome to GeeksForGeeks
This is Geek1
21 and 23 are lucky geek numbers !!