Dart 编程 - 类型定义 (Typedef)



**typedef**,或称为函数类型别名,有助于定义指向内存中可执行代码的指针。简单来说,**typedef** 可以用作引用函数的指针。

以下是 Dart 程序中实现 **typedef** 的步骤。

步骤 1:定义 typedef

**typedef** 可以用于指定我们希望特定函数匹配的函数签名。函数签名由函数的参数(包括其类型)定义。返回值类型不是函数签名的一部分。其语法如下所示。

typedef function_name(parameters)

步骤 2:将函数分配给 typedef 变量

**typedef** 的变量可以指向任何具有与 **typedef** 相同签名的函数。您可以使用以下签名将函数分配给 **typedef** 变量。

type_def  var_name = function_name

步骤 3:调用函数

**typedef** 变量可以用来调用函数。以下是调用函数的方法:

var_name(parameters) 

示例

现在让我们来看一个例子,以便更好地理解 Dart 中的 **typedef**。

首先,让我们定义一个 **typedef**。这里我们定义了一个函数签名。该函数将接收两个类型为 **整数** 的输入参数。返回值类型不是函数签名的一部分。

typedef ManyOperation(int firstNo , int secondNo); //function signature

接下来,让我们定义函数。定义一些与 **ManyOperation typedef** 函数签名相同的函数。

Add(int firstNo,int second){ 
   print("Add result is ${firstNo+second}"); 
}  
Subtract(int firstNo,int second){ 
   print("Subtract result is ${firstNo-second}"); 
}  
Divide(int firstNo,int second){ 
   print("Add result is ${firstNo/second}"); 
}

最后,我们将通过 **typedef** 调用函数。声明一个 ManyOperations 类型的变量。将函数名称分配给声明的变量。

ManyOperation oper ;  

//can point to any method of same signature 
oper = Add; 
oper(10,20); 
oper = Subtract; 
oper(30,20); 
oper = Divide; 
oper(50,5); 

**oper** 变量可以指向任何接收两个整数参数的方法。**Add** 函数的引用被分配给该变量。Typedef 可以运行时切换函数引用

现在让我们将所有部分放在一起,看看完整的程序。

typedef ManyOperation(int firstNo , int secondNo); 
//function signature  

Add(int firstNo,int second){ 
   print("Add result is ${firstNo+second}"); 
} 
Subtract(int firstNo,int second){ 
   print("Subtract result is ${firstNo-second}"); 
}
Divide(int firstNo,int second){ 
   print("Divide result is ${firstNo/second}"); 
}  
Calculator(int a, int b, ManyOperation oper){ 
   print("Inside calculator"); 
   oper(a,b); 
}  
void main(){ 
   ManyOperation oper = Add; 
   oper(10,20); 
   oper = Subtract; 
   oper(30,20); 
   oper = Divide; 
   oper(50,5); 
} 

程序应产生以下 **输出**:

Add result is 30 
Subtract result is 10 
Divide result is 10.0 

**注意** - 如果 **typedef** 变量尝试指向具有不同函数签名的函数,则上述代码将导致错误。

示例

**Typedef** 也可以作为参数传递给函数。请考虑以下示例:

typedef ManyOperation(int firstNo , int secondNo);   //function signature 
Add(int firstNo,int second){ 
   print("Add result is ${firstNo+second}"); 
}  
Subtract(int firstNo,int second){
   print("Subtract result is ${firstNo-second}"); 
}  
Divide(int firstNo,int second){ 
   print("Divide result is ${firstNo/second}"); 
}  
Calculator(int a,int b ,ManyOperation oper){ 
   print("Inside calculator"); 
   oper(a,b); 
}  
main(){ 
   Calculator(5,5,Add); 
   Calculator(5,5,Subtract); 
   Calculator(5,5,Divide); 
} 

它将产生以下 **输出**:

Inside calculator 
Add result is 10 
Inside calculator 
Subtract result is 0 
Inside calculator 
Divide result is 1.0
广告