簡體   English   中英

在Dart中,子類如何擴展超類,具有子類的泛型類型擴展了超類的類型?

[英]In Dart, how can a subclass extend a superclass, having a generic type of the subclass extend a type of the superclass?

這是一個Dart泛型問題。 這個問題似乎比較簡單,請繼續閱讀。

我有:

  • class SomeController使用類型T.
  • class ExtendedController使用類型S.
  • ExtendedController擴展了SomeController
  • S延伸T.

以下代碼不起作用:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM