[英]defining a generic class with parametrized type that expects more than one abstract class implementation in dart
interfaces接口
abstract class Adder<T> {
T add(T a, T b);
}
abstract class Multiplier<T> {
T multiply(T a, T b);
}
abstract class Displayer<T> {
void display(T a);
}
An implementation that just happens to implement all three.一个恰好实现了所有三个的实现。
class IntImpl implements Adder<int>, Multiplier<int>, Displayer<int> {
@override
int add(int a, int b) {
return a + b;
}
@override
int multiply(int a, int b) {
return a * b;
}
@override
void display(int a) {
print('printing: ${a}');
}
}
A consumer that needs support for two of the interfaces.需要支持其中两个接口的使用者。 But, I could not find how to declare such a thing.但是,我找不到如何声明这样的事情。
class DisplayingAdder<T, K extends Adder<T>> {
final K engine;
DisplayingAdder(this.engine);
T addAndDisplay(T a, T b) {
final r = engine.add(a, b);
// How do I change DisplayingAdder class parametrization to make the next line functional?
// engine.display(r);
return r;
}
}
Code to exercise the above执行上述操作的代码
void main() {
final e1 = IntImpl();
final da = DisplayingAdder(e1);
da.addAndDisplay(3,4);
}
Not sure what can be changed to allow the generic parameter to declare support for more than one abstract class.不确定可以更改什么以允许泛型参数声明对多个抽象类的支持。
You can't restrict a generic type to a type that implements multiple supertypes.您不能将泛型类型限制为实现多个超类型的类型。 The best you're going to have to do is separate engine
into an object that implements Adder
and an object that implements Displayer
, then pass the instance of IntImpl
to both.您要做的最好的事情是将engine
分成一个实现Adder
的对象和一个实现Displayer
的对象,然后将IntImpl
的实例IntImpl
给两者。 (This is more scalable anyway since it also allows you to pass different values to each if you wanted.) (无论如何,这更具可扩展性,因为它还允许您根据需要将不同的值传递给每个值。)
class DisplayingAdder<T, A extends Adder<T>, D extends Displayer<T>> {
final A adder;
final D displayer;
DisplayingAdder(this.adder, this.displayer);
T addAndDisplay(T a, T b) {
final r = adder.add(a, b);
displayer.display(r);
return r;
}
}
void main() {
final e1 = IntImpl();
final da = DisplayingAdder(e1, e1);
da.addAndDisplay(3,4);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.