我定义了一个这样的类,并用冻结的库进行了注释。
@freezed
@immutable
abstract class CommentMediaAttachmentModel with _$CommentMediaAttachmentModel {
const factory CommentMediaAttachmentModel({
final String type,
final String mediaUrl,
final int width,
final int height
}) = _CommentMediaAttachmentModel;
bool isAnimated() {
return type == 'ANIMATED';
}
}
Run Code Online (Sandbox Code Playgroud)
我想添加一个快速函数isAnimated
来确定type
变量,但在编译时,它不允许我这样做:
lib/presentation/comment/model/comment_attachment_model.freezed.dart:292:7: Error: The non-abstract class '_$_CommentMediaAttachmentModel' is missing implementations for these members:
- CommentMediaAttachmentModel.isAnimated
Try to either
- provide an implementation,
- inherit an implementation from a superclass or mixin,
- mark the class as abstract, or …
Run Code Online (Sandbox Code Playgroud) 我目前正在实现一个函数,使用超类作为参数.
例如:
private void foo(Parent parent) {
if(parent.getClass() == Child1.class) {
Child1 c1 = (Child1) parent;
System.out.println(c1.getChild1Attribute());
}
else if(parent.getClass() == Child2.class) {
Child2 c2 = (Child2) parent;
System.out.println(c1.getChild2Attribute());
}
else if(parent.getClass() == Parent.class) {
System.out.println(parent.getParentAttribute());
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个坏主意吗?
我在这里读到了一些线索,说使用getClass()
或是instanceof
不好的设计: