问题描述
我有一个问题要从抽象类中重写泛型方法.
I have an issue to override a generic method from an abstract class.
这是我的抽象课:
abstract class A {
String getData<Type>(Type key);
}
当我创建一个类(B)来实现类(A)时,如下所示:
when I created a class (B) to implement class (A) as showing below:
class B implements A {
@override
String getData<String>(String key) { //Error <= B.getData' ('String Function<String>(String)') isn't a valid override of 'A.getData' ('String Function<Type>(Type)')
return "";
}
}
在(getData)方法中显示以下编译错误:
Shown the below compilation error at (getData) method:
返回语句中的错误:
当通用类型类似于返回类型时,为什么我会得到与覆盖相关的错误,这使我感到困惑.当我用 getData< int>(int键)
而不是 getData< String>(String键)
创建另一个类(C)时,一切按预期进行:
It's confusing for me why I am getting this error related to the override when the generic type similar to return type. as when I created another class (C) with getData<int>(int key)
instead of getData<String>(String key)
everything works as expected:
class C implements A {
@override
String getData<int>(int key) {
return "";
}
}
如果我删除了如下所示的返回类型,则使用(B)类,一切都会按预期进行:
Also with the class (B) if I deleted the return type as shown below everything will work as expected:
class B implements A {
@override
getData<String>(String key) {
return "";
}
}
这在Dart设计中是否是一个问题,所以我可以意识到,因为这种行为例如在c#语言中不存在?
Is it an issue in Dart design so I can be aware of it because this behavior does not exist in c# language for example?
DartPad链接: https://dartpad.dev/ebc7e6361d0cf1c6afad2f52ab8ebcaa
推荐答案
方法签名
String getData<Type>(Type key);
由于 Type
已经具有含义.
String getData<T>(T key);
此签名用于允许为 T
填写任何类型的方法.这意味着每个子类都必须具有允许 any 类型 T
的方法.
This signature is for a method that allows any type to be filled in for T
. This means that every subclass must have a method that allows for any type T
.
我怀疑您想要的是将子类专用于单个泛型类型-在这种情况下,您希望将泛型从方法级别移至类级别.
I suspect that what you want is for subclasses to be specialized to a single generic type - in that case you want to move the generic from the method level to the class level.
abstract class A<T> {
String getData(T key);
}
class B implements A<String> {
@override
String getData(String key) => '';
}
class C implements A<int> {
@override
String getData(int key) => '';
}
这篇关于Dart:不重写泛型方法具有与返回类型相似的泛型参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!