如何使用dart实施委托/代理? [英] How to use dart to implement a delegate/proxy?

查看:440
本文介绍了如何使用dart实施委托/代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类 Parser Proxy ,当我从调用方法时解析器(不存在),它将把它委托给 Proxy 类。

I have two classes Parser and Proxy, and when I invoke a method from Parser, which does not exist, it will delegate it to Proxy class.

我的代码:

class Parser {
    noSuchMethod(Invocation invocation) {
        // how to pass the `invocation` to `Proxy`???
    }
}

class Proxy {
    static String hello() { return "hello"; }
    static String world() { return "world"; }
}

在我写的时候:

var parser = new Parser();
print(parser.hello());

它将打印:

hello


推荐答案

使用 dart:mirrors 。操作方法如下:

import 'dart:mirrors';

class Parser {
  noSuchMethod(Invocation invocation) {
    ClassMirror cm = reflectClass(Proxy);
    return cm.invoke(invocation.memberName
        , invocation.positionalArguments
        /*, invocation.namedArguments*/ // not implemented yet
        ).reflectee;
  }
}

class Proxy {
  static String hello() { return "hello"; }
  static String world() { return "world"; }
}

main(){
  var parser = new Parser();
  print(parser.hello());
  print(parser.world());
}

这篇关于如何使用dart实施委托/代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆