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