问题描述
我有一堂课:
abstract class Foo {
String getName(T f);
}
和:
class Bar implements Foo {}
或
class Bar extends Foo {}
Foo
如何知道 Bar
并将 T
实现为 Bar
?
更新: 我考虑过静态传递孩子的类型,例如:
@override
String getName<Bar>(Bar p1) {
return p1.name;
}
这样我就遇到了这个错误:The property 'name' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').
所以,我将其编辑为:
@override
String getName<Bar>(Bar p1) {
return p1!.name;
}
现在我收到此错误:The getter 'name' isn't defined for the type 'Bar & Object'. Try importing the library that defines 'name',correcting the name to the name of an existing getter,or defining a getter or field named 'name'.
我想目前唯一的解决方案是使用 dynamic
类型,如下所示:
abstract class Foo {
String getName(f);
}
和
class Bar implements Foo {
@override
String getName(f) {
return (f as Bar).name;
}
}
但我真的很想知道这个问题的答案。
解决方法
abstract class Foo {
String getName(T f);
}
应该无效。 T
未在任何地方指定。
你需要为泛型指定一个地方传递:
abstract class Foo<T> {
String getName(T f);
}
然后在扩展/实现抽象类时传递泛型:
abstract class Foo<T> {
String getName(T f);
}
class Bar implements Foo<Bar> {
final String name = '';
@override
String getName(Bar p1) {
return p1.name;
}
}
如果 getName
将始终接受 Foo
的实现者,您可以删除泛型并改为使用 covariant
关键字:
abstract class Foo {
String getName(covariant Foo f);
}
class Bar implements Foo {
final String name = '';
@override
String getName(Bar p1) {
return p1.name;
}
}