[英]how to get the extender or implementer child's Type
I have a class:我有一个 class:
abstract class Foo {
String getName(T f);
}
and:和:
class Bar implements Foo {}
or或者
class Bar extends Foo {}
how can Foo
know Bar
and implement T
as Bar
? Foo
怎么知道Bar
并将T
实现为Bar
?
UPDATE : I considered statically passing the type of the child, like:更新:我考虑静态传递孩子的类型,例如:
@override
String getName<Bar>(Bar p1) {
return p1.name;
}
this way I ran into this error: 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 ('.').
这样我遇到了这个错误:
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 ('.').
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 ('.').
so, I edited it to be:所以,我将其编辑为:
@override
String getName<Bar>(Bar p1) {
return p1!.name;
}
and now I'm getting this error: 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'.
现在我收到了这个错误:
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'.
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'.
I guess the only solution, for now, is using dynamic
type, like this:我想目前唯一的解决方案是使用
dynamic
类型,如下所示:
abstract class Foo {
String getName(f);
}
and和
class Bar implements Foo {
@override
String getName(f) {
return (f as Bar).name;
}
}
but I'd really like to know the answer to this question.但我真的很想知道这个问题的答案。
abstract class Foo {
String getName(T f);
}
should not be valid.不应该是有效的。
T
is not specified anywhere. T
没有在任何地方指定。
You need to specify a place for the generic to be passed:您需要为要传递的泛型指定一个位置:
abstract class Foo<T> {
String getName(T f);
}
Then pass that generic when you extend/implement the abstract class:然后在扩展/实现抽象 class 时传递该泛型:
abstract class Foo<T> {
String getName(T f);
}
class Bar implements Foo<Bar> {
final String name = '';
@override
String getName(Bar p1) {
return p1.name;
}
}
If getName
will always accept an implementer of Foo
, you can remove the generic and instead use the covariant
keyword:如果
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.