首页 文章

Dart中命名和可选参数之间有什么区别?

提问于
浏览
46

Dart支持命名的可选参数和位置可选参数 . 两者有什么不同?

另外,如何判断是否实际指定了可选参数?

2 回答

  • 80

    Dart有两种可选参数:命名和位置 . 在讨论差异之前,让我先讨论相似之处 .

    Dart的可选参数是可选的,因为调用者在调用函数时不需要为参数指定值 .

    可选参数只能在任何必需参数之后声明 .

    可选参数可以具有默认值,当调用者未指定值时使用该值 .

    Positional optional parameters

    [ ] 包装的参数是位置可选参数 . 这是一个例子:

    getHttpUrl(String server, String path, [int port=80]) {
      // ...
    }
    

    在上面的代码中, port 是可选的,默认值为 80 .

    您可以使用或不使用第三个参数调用 getHttpUrl .

    getHttpUrl('example.com', '/index.html', 8080); // port == 8080
    getHttpUrl('example.com', '/index.html');       // port == 80
    

    您可以为函数指定多个位置参数:

    getHttpUrl(String server, String path, [int port=80, int numRetries=3]) {
      // ...
    }
    

    可选参数的位置是,如果要指定 numRetries ,则不能省略 port .

    getHttpUrl('example.com', '/index.html');
    getHttpUrl('example.com', '/index.html', 8080);
    getHttpUrl('example.com', '/index.html', 8080, 5);
    

    当然,除非你知道8080和5是什么,否则很难说出那些看似神奇的数字是什么 . 您可以使用命名的可选参数来创建更具可读性的API .

    Named optional parameters

    { } 包装的参数是命名的可选参数 . 这是一个例子:

    getHttpUrl(String server, String path, {int port: 80}) {
      // ...
    }
    

    您可以使用或不使用第三个参数调用 getHttpUrl . 您 must 在调用函数时使用参数名称 .

    getHttpUrl('example.com', '/index.html', port: 8080); // port == 8080
    getHttpUrl('example.com', '/index.html');             // port == 80
    

    您可以为函数指定多个命名参数:

    getHttpUrl(String server, String path, {int port: 80, int numRetries: 3}) {
      // ...
    }
    

    由于命名参数是按名称引用的,因此可以按与其声明不同的顺序使用它们 .

    getHttpUrl('example.com', '/index.html');
    getHttpUrl('example.com', '/index.html', port: 8080);
    getHttpUrl('example.com', '/index.html', port: 8080, numRetries: 5);
    getHttpUrl('example.com', '/index.html', numRetries: 5, port: 8080);
    getHttpUrl('example.com', '/index.html', numRetries: 5);
    

    我相信命名参数有助于更容易理解的调用站点,尤其是当存在布尔标志或不符合上下文的数字时 .

    Checking if optional parameter was provided

    遗憾的是,您无法区分“未提供可选参数”和“使用默认值提供可选参数”的情况 .

    Note: 您可以使用位置可选参数 or 命名的可选参数,但不能同时使用相同的函数或方法 . 以下是不允许的 .

    thisFunctionWontWork(String foo, [String positonal], {String named}) {
      // will not work!
    }
    
  • 1

    当使用“paramName:value”语法指定函数的参数时,它是一个命名参数 . 这些参数可以通过将它们括在[和]括号之间来呈现 . 可以在以下Hello World程序中演示此功能的基本演示:

    sayHello([String name = ' World!']) {
      print('Hello, ${name}');
    }
    
    void main() {
      sayHello('Govind');
    }
    

相关问题