测试Dart值是否实际上是一个函数?

Phi*_*ght 3 types function dart

是否可以测试值是否是可以调用的函数?我可以轻松地测试null,但之后我不知道如何确保传入的参数实际上是一个函数?

void myMethod(funcParam)
{
   if (funcParam != null)
   {
       /* How to test if funcParam is actually a function that can be called? */
       funcParam();
   }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ioP 6

void myMethod(funcParam) {
    if(funcParam is Function) {
        funcParam();
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,调用funcParams()仅在参数列表匹配时才起作用 - is Function不会检查它.如果涉及参数,可以使用typedef来确保这一点.

typedef void MyExpectedFunction(int someInt, String someString);

void myMethod(MyExpectedFunction funcParam, int intParam, String stringParam) {
    if(funcParam is MyExpectedFunction) {
        funcParam(intParam, stringParam);
    }
}
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 3

  var f = () {};
  print(f is Function); // 'true'

  var x = (x){};
  print(x is Function); // 'true'
Run Code Online (Sandbox Code Playgroud)