目录

dart_programming编程 - Typedef(Typedef)

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

下面给出了在Dart程序中实现typedefs的步骤。

Step 1: Defining a typedef

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

typedef function_name(parameters)

Step 2: Assigning a Function to a typedef Variable

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

type_def  var_name = function_name

Step 3: Invoking a Function

typedef变量可用于调用函数。 以下是调用函数的方法 -

var_name(parameters) 

例子 (Example)

现在让我们举一个例子来了解Dart中关于typedef更多信息。

首先,让我们定义一个typedef 。 这里我们定义一个函数签名。 该函数将采用integer类型的两个输入参数。 返回类型不是函数签名的一部分。

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); 
} 

该程序应产生以下output -

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

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

例子 (Example)

Typedefs也可以作为参数传递给函数。 考虑以下示例 -

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); 
} 

它将产生以下output -

Inside calculator 
Add result is 10 
Inside calculator 
Subtract result is 0 
Inside calculator 
Divide result is 1.0
↑回到顶部↑
WIKI教程 @2018