首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >飞镖里的NoSuchMethod?

飞镖里的NoSuchMethod?
EN

Stack Overflow用户
提问于 2018-12-13 11:53:34
回答 1查看 4.3K关注 0票数 5

在尝试使用noSuchMethod().时得到警告

未为类Person定义缺少的方法。

但是根据docs和其他示例,无论何时我们调用一个不存在的成员,都应该调用noSuchMethod()。其默认行为是抛出noSuchMethodError。

代码语言:javascript
复制
 void main() {
    var person = new Person();
    print(person.missing("20", "Shubham")); // is a missing method!
 }

 class Person {

    @override
    noSuchMethod(Invocation msg) => "got ${msg.memberName} "
                      "with arguments ${msg.positionalArguments}";

 } 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-13 16:11:14

根据用于调用未实现方法的正式文档,必须满足以下几点之一:

  • 接收机具有静态类型动态。
  • 接收器有一个静态类型,它定义未实现的方法(抽象是OK),而接收器的动态类型有一个noSuchMethod()的实现,这与类对象中的实现不同。

示例1: Satifies

代码语言:javascript
复制
class Person {
  @override  //overring noSuchMethod
    noSuchMethod(Invocation invocation) => 'Got the ${invocation.memberName} with arguments ${invocation.positionalArguments}';
}

main(List<String> args) {
  dynamic person = new Person(); // person is declared dynamic hence staifies the first point
  print(person.missing('20','shubham'));  //We are calling an unimplemented method called 'missing'
}

示例2: Satifies第二

代码语言:javascript
复制
class Person {
  missing(int age,String name);

  @override //overriding noSuchMethod
    noSuchMethod(Invocation invocation) => 'Got the ${invocation.memberName} with arguments ${invocation.positionalArguments}';
}

main(List<String> args) {
  dynamic person = new Person(); //person could be var, Person or dynamic
  print(person.missing(20,'shubham')); //calling abstract method
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53761294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档