dart:代理注解用法

dart: proxy annotation usage

@proxy 注释的文档说明:

If a class is annotated with @proxy, or it implements any class that is annotated, then the class is considered to implement any interface and any member with regard to static type analysis. As such, it is not a static type warning to assign the object to a variable of any type, and it is not a static type warning to access any member of the object.

但是,给定以下代码:

import 'dart:mirrors';

@proxy
class ObjectProxy{
  final InstanceMirror _mirror;

  ObjectProxy(Object o): _mirror = reflect(o);

  @override
  noSuchMethod(Invocation invocation){
    print('entered ${invocation.memberName}');
    var r = _mirror.delegate(invocation);
    print('returning from ${invocation.memberName} with $r');
    return r;
  }
}

class ClassA{
  int k;

  ClassA(this.k);
}

void printK(ClassA a) => print(a.k);

main() {
  ClassA a = new ObjectProxy(new ClassA(1)); //annoying
  printK(a);
}

dart 编辑器警告

A value of type 'ObjectProxy' cannot be assigned to a variable of type 'ClassA'.

代码在未检查模式下按预期执行,但警告很烦人,据我所知,抑制该警告是 @proxy 标记唯一应该做的事情。

我是否误解了 @proxy 标签的用法,或者这是 dart editor/analyzer 的错误?

你能做的是

@proxy
class ObjectProxy implements ClassA {
  final InstanceMirror _mirror;

  ObjectProxy(Object o): _mirror = reflect(o);

  @override
  noSuchMethod(Invocation invocation){
    print('entered ${invocation.memberName}');
    var r = _mirror.delegate(invocation);
    print('returning from ${invocation.memberName} with $r');
    return r;
  }
}

您需要声明 ObjectProxy 实现了一个接口,但您不必实际实现它。 如果您认为这是一个错误,请在 http://dartbug.com

报告它