Dart中的函数

2019-08-21  本文已影响0人  iDevOps
定义函数
返回值类型  方法名 (参数){
    方法体
    return 返回值;
}
int test(int a, int b){
  return a + b;
}

main(){
  int a = 1;
  int b = 2;
  int c = test(a, b);
  print(c); //3
}
函数参数
void test(int a, {int b, String c}){
  print("$a  $b  $c");
}

main(){
  test(1); //1  null  null
  test(1, b:2); //1  2  null
  test(1, c:'hello'); //1  null  hello
  test(1, b:2, c:'hello'); //1  2  hello
}
void test(int a, [int b, String c]){
  print("$a  $b  $c");
}

main(){
  test(1); //1  null  null
  test(1, 2); //1  2  null
  test(1, 2, 'hello'); //1  2  hello
}
void test(int a, {int b=3}){
  print("$a  $b");
}

main(){
  test(1); //1  3
}
main(){
  //1. 方法作为对象赋值给其他变量
  Function f1 = sayHello;
  f1(); //sayHello方法调用, 输出hello

  //2. 方法作为参数传递给其他方法
  testSayHello(sayHello); //hello
}

void sayHello(){
  print("hello");
}

void testSayHello(Function sayHello){
  sayHello();
}
main(){
  //定义匿名函数
  var f1 = (String str){
    print("Hello $str");
  };
  f1("Dart"); //Hello Dart
}
上一篇 下一篇

猜你喜欢

热点阅读