扩展一个只有一个工厂构造函数

扩展一个只有一个工厂构造函数

本文介绍了扩展一个只有一个工厂构造函数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪个是扩展 CustomEvent 类的最好方法,这个类只有一个工厂构造函数。我试着做以下和遇到一个问题与超级构造函数:

  class MyExtendedEvent extends CustomEvent {
int count;

factory MyExtendedEvent(num count){
return new MyExtendedEvent._internal(1);
}

MyExtendedEvent._internal(num count){
this.count = count;
}
}

但我无法使用。我总是遇到:

如果我尝试内部构造函数:

  MyExtendedEvent._internal(num count):super('MyCustomEvent'){
this.count = count;
}

我最后得到:


$ b $


I'b 我不知道我在做什么 - 但我想问题是 CustomEvent 只有一个构造函数是一个工厂构造函数(如doc说 - )



扩展 CustomEvent 或此表单的任何类别的最佳方法是什么?

解决方案

您不能使用工厂构造函数直接延伸类。



例如:


$ b $

  class MyExtendedEvent implements CustomEvent {
int count;
final CustomEvent _delegate;

MyExtendedEvent(this.count,String type):
_delegate = new CustomEvent(type);

noSuchMethod(Invocation invocation)=>
reflect(_delegate).delegate(invocation);
}



NB:我在这里使用反射来简化代码片段。一个更好的实现(关于性能)将定义所有的方法,例如 method1 => _delegate.method1()


I was wondering which is the best way to extend the CustomEvent class, a class which has only one factory constructor. I tried doing the following and ran into an issue with the super constructor :

class MyExtendedEvent extends CustomEvent {
  int count;

  factory MyExtendedEvent(num count) {
    return new MyExtendedEvent._internal(1);
  }

  MyExtendedEvent._internal(num count) {
    this.count = count;
  }
}

but I can't get it working. I always run into :

If i try chaning the internal constructor to :

MyExtendedEvent._internal(num count) : super('MyCustomEvent') {
  this.count = count;
}

I end up with :

I'm not sure what I'm doing wrong - but I guess the problem is that the CustomEvent has only one constructor which is a factory constructor (as doc says - http://api.dartlang.org/docs/releases/latest/dart_html/CustomEvent.html)

What is the best way to extend a CustomEvent, or any class of this form?

解决方案

You can't directly extend a class with a factory constructor. However you can implement the class and use delegation to simulate the extension.

For instance :

class MyExtendedEvent implements CustomEvent {
  int count;
  final CustomEvent _delegate;

  MyExtendedEvent(this.count, String type) :
    _delegate = new CustomEvent(type);

  noSuchMethod(Invocation invocation) =>
      reflect(_delegate).delegate(invocation);
}

NB : I used reflection here to simplify the code snippet. A better implementation (in regard of performances) would have been to define all methods like method1 => _delegate.method1()

这篇关于扩展一个只有一个工厂构造函数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:59