[英]In Dart, how can a subclass extend a superclass, having a generic type of the subclass extend a type of the superclass?
這是一個Dart泛型問題。 這個問題似乎比較簡單,請繼續閱讀。
我有:
以下代碼不起作用:
import 'package:flutter/material.dart';
class SomeValue {}
class ExtendedValue extends SomeValue {}
abstract class SomeController<T extends SomeValue> extends ValueNotifier<T> {
SomeController(T value) : super(value);
factory SomeController.create() {
return ExtendedController();
}
}
class ExtendedController extends SomeController<ExtendedValue> {
ExtendedController() : super(ExtendedValue());
}
我收到錯誤:
The return type 'ExtendedController' isn't a 'SomeController<T>', as defined by the method 'create'.
在return ExtendedController();
線。
然后我把它改成了這個:
import 'package:flutter/material.dart';
class SomeValue {}
class ExtendedValue extends SomeValue {}
abstract class SomeController<T extends SomeValue> extends ValueNotifier<T> {
SomeController(T value) : super(value);
factory SomeController.create() {
return ExtendedController();
}
}
class ExtendedController<S extends ExtendedValue> extends SomeController<S> {
ExtendedController() : super(ExtendedValue());
}
仍然不起作用,但現在我得到另一個錯誤: The constructor returns type 'ExtendedValue' that isn't of expected type 'S'.
這次是在super(ExtendedValue());
線。
一個顯式的演員修復它:
factory SomeController.create() {
return ExtendedController() as SomeController<T>;
}
https://groups.google.com/a/dartlang.org/forum/#!topic/misc/bVRHdagR8Tw
或者你可以使用
static create() {
return ExtendedController() as SomeController<T>;
}
隨着可選的new
,沒有任何區別了。
我們來看第一個錯誤: The return type 'ExtendedController' isn't a 'SomeController<T>', as defined by the method 'create'.
根據定義,它告訴ExtendedController
不是 create
方法的預期返回類型 。
create
是一個工廠方法,並期望返回類型為SomeController
factory SomeController.create() {
return SomeController();
}
我們也不能像這樣改變,因為SomeController
是一個抽象類。 所以,我將factory
方法移動到ExtendedController。
class SomeValue {}
class ExtendedValue extends SomeValue {}
abstract class SomeController<T extends SomeValue> extends ValueNotifier<T> {
SomeController(T value) : super(value);
}
class ExtendedController extends SomeController {
ExtendedController(ExtendedValue value) : super(value);
factory ExtendedController.create() {
return ExtendedController(ExtendedValue());
}
}
希望我的解釋在某種程度上有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.