我的目标是创建一个rename
返回类类型本身的方法。但这rename
是一个要在基类中定义的接口,以便基类可以使用它。
void main() {
Cat cat = Cat("Whiskers");
Dog dog = Dog("Buddy");
Cat renamedCat = cat.rename("Mittens");
Dog renamedDog = dog.rename("Max");
print("Old cat name: ${cat.name}, New cat name: ${renamedCat.name}");
print("Old dog name: ${dog.name}, New dog name: ${renamedDog.name}");
}
这两个版本都不起作用。
版本 1:
abstract class Animal {
final String name;
Animal(this.name);
T copyWith<T extends Animal>({String? name});
}
class Cat extends Animal {
Cat(super.name);
@override
Cat copyWith({String? name}) {
return Cat(name ?? this.name);
}
}
class Dog extends Animal {
Dog(super.name);
@override
Dog copyWith({String? name}) {
return Dog(name ?? this.name);
}
}
extension AnimalExtension<T extends Animal> on T {
T rename(String newName) {
return copyWith(name: newName);
}
}
出现此错误:
Cat.copyWith' ('Cat Function({String? name})') isn't a valid override of 'Animal.copyWith' ('T Function<T extends Animal>({String? name})').
版本 2:
abstract class Animal {
final String name;
Animal(this.name);
Animal copyWith({String? name});
}
class Cat extends Animal {
Cat(super.name);
@override
Cat copyWith({String? name}) {
return Cat(name ?? this.name);
}
}
class Dog extends Animal {
Dog(super.name);
@override
Dog copyWith({String? name}) {
return Dog(name ?? this.name);
}
}
extension AnimalExtension<T extends Animal> on T {
T rename(String newName) {
return copyWith(name: newName);
}
}
给出错误:
无法从方法“rename”返回“Animal”类型的值,因为它的返回类型为“T
有一个可行的解决方案,但我不喜欢,它味道很重,因为它是糟糕的编程:
return copyWith(name: newName) as T; // this just forces it to work