强制子类重写方法
如何才能使从我的基类继承的任何类都强制重写特定方法?我不想使用协议,因为这不会使这种行为自动化。
@interface MyBaseClass : NSObject
{
}
- (void)performAnAction;
@end
@implementation MyBaseClass
- (void)performAnAction
{
@throw([NSException exceptionWith...]);
}
@end
How can I make it so that any class that inherits from my base class is forced to override a specific method? I don't want to use a protocol, because that wouldn't make this behavior automated.
@interface MyBaseClass : NSObject
{
}
- (void)performAnAction;
@end
@implementation MyBaseClass
- (void)performAnAction
{
@throw([NSException exceptionWith...]);
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你到底是什么意思,强迫他们覆盖它?如果您只是像这样实现父方法:
那么如果子类无法重写它,它将在运行时抛出异常。不幸的是,没有办法在编译时强制执行这一点。
How exactly do you mean, force them to override it? If you simply implement the parent method like so:
then it'll throw an exception at runtime if the child class fails to override it. Unfortunately there is no way to enforce this at compile-time.
你可以抛出一个异常。只要有详细记录,那么在我看来,这是对异常的合理使用,因为它确实是一个编程错误。
You could just throw an exception. As long as this is well documented, then IMO this is a reasonable use of exceptions since it truly is a programming error.