Flutter Dart 引用方法 带括号 和 不带括号的比较

通过代码比较一下

class Person {
  bool say(String msg) {
    print(msg);
    return msg == null ? false : true;
  }

  void setPeople() {
    /**
     *  People.setSay1 参数需要是一个bool值
     *  say("im people")带括号就相当于调用方法拿到返回bool值
     *  所以没问题 
     *  */
    new People.setSay1(isSay: say("im people"));

    /**
     *  People.setSay2 参数是需要 bool Function(String)
     *  say("im people")带括号就是一个bool值
     *  所以会报错
     *  The argument type 'bool' can't be assigned to 
     *  the parameter type 'bool Function(String)'.dartargument_type_not_assignable
     *  */
    new People.setSay2(methodSay: say("im people"));

    /**
     * 直接用 say方法,不带括号不传参数,就代表的了say方法本身
     * say方法 结构就是bool Function(String)
     * 所以没问题
     */
    new People.setSay2(methodSay: say);
  }
}

typedef MethodSay = bool Function(String msg);

class People {
  String peopleSayMsg;
  bool isSay;
  People.setSay1({bool isSay}) {
    this.isSay = isSay;
  }
  People.setSay2({MethodSay methodSay}) {
    methodSay(peopleSayMsg);
  }
}

总结:

方法名( 参数 )    这样使用就相当于调用方法后的得到的值,这个方法返回类型是什么  就是一个什么类型的值

方法名                直接用,不加括号       就是这个方法本身结构传过去 ,而不是其运算后的返回值

猜你喜欢

转载自blog.csdn.net/u011288271/article/details/106100410
今日推荐