📜  Dart中可调用类的概念

📅  最后修改于: 2021-09-02 05:07:55             🧑  作者: Mango

Dart允许用户创建一个可调用的类该类允许将的实例作为函数。要允许像函数一样调用Dart类的实例,请实现call() 方法

句法:

class class_name {
  ... // class content
  
  return_type call ( parameters ) {
    ... // call function content
  }
  
}

在上面的语法中,我们可以看到要创建一个可调用的类,我们必须定义一个带有返回类型和参数的调用方法。

示例 1:在Dart实现可调用类。

Dart
// Creating Class GeeksForGeeks
class GeeksForGeeks {
    
  // Defining call method which create the class callable
  String call(String a, String b, String c) => 'Welcome to $a$b$c!';
}
  
// Main Function
void main() {
  // Creating instance of class
  var geek_input = GeeksForGeeks();
    
  // Calling the class through its instance
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
    
  // Printing the output
  print(geek_output);
}


Dart
// Creating Class GeeksForGeeks
class GeeksForGeeks {
  // Defining call method which create the class callable
  String call(String a, String b, String c) => 'Welcome to $a$b$c!';
    
  // Defining another call method for the same class
  String call(String a) => 'Welcome to $a!';
}
  
// Main Function
void main() {
  // Creating instance of class
  var geek_input = GeeksForGeeks();
    
  // Calling the class through its instance
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
    
  // Printing the output
  print(geek_output);
}


输出:

Welcome to GeeksForGeeks!

必须注意的是, Dart不支持多个可调用方法,即如果我们尝试为同一个类创建多个可调用函数,它将显示错误

示例 2:在Dart类中实现多个可调用函数。

Dart

// Creating Class GeeksForGeeks
class GeeksForGeeks {
  // Defining call method which create the class callable
  String call(String a, String b, String c) => 'Welcome to $a$b$c!';
    
  // Defining another call method for the same class
  String call(String a) => 'Welcome to $a!';
}
  
// Main Function
void main() {
  // Creating instance of class
  var geek_input = GeeksForGeeks();
    
  // Calling the class through its instance
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
    
  // Printing the output
  print(geek_output);
}

输出:

Error compiling to JavaScript:
main.dart:3:10:
Error: 'call' is already declared in this scope.
  String call(String a) => 'Welcome to $a!';
         ^^^^
main.dart:2:10:
Info: Previous declaration of 'call'.
  String call(String a, String b, String c) => 'Welcome to $a$b$c!';
         ^^^^
main.dart:8:31:
Error: Can't use 'call' because it is declared more than once.
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
                              ^^^^
main.dart:8:31:
Error: The method 'call' isn't defined for the class 'GeeksForGeeks'.
 - 'GeeksForGeeks' is from 'main.dart'.
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
                              ^
Error: Compilation failed.