我可以强制子类覆盖方法没有使它抽象? [英] Can I force subclasses to override a method without making it abstract?

查看:98
本文介绍了我可以强制子类覆盖方法没有使它抽象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类用一些抽象方法,但我希望能够编辑类的子类的设计师。然而,设计者无法编辑的子类,除非它可以创建一个父类的一个实例。所以,我的计划是用存根替换的抽象方法,并将其标记为虚拟的 - 但如果我再拍的子类,我不会得到一个编译时错误,如果我忘了执行这些

I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.

有没有一种方法来标记,使他们由子类实现的方法,而不将它们标记为抽象的?

Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?

推荐答案

那么你可以做一些非常凌乱code,涉及#如果 - 即在 DEBUG 是虚拟(对于设计师),但在发布它是抽象的。一个真正的痛苦来维持,虽然。

Well you could do some really messy code involving #if - i.e. in DEBUG it is virtual (for the designer), but in RELEASE it is abstract. A real pain to maintain, though.

但除此之外:基本上没有。如果你想设计器支持它不能是抽象的,所以你只剩下虚拟(presumably与基本方法抛出一个 NotImplementedException

But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a NotImplementedException).

当然,你的单元测试将检查方法已经实施,是吗? ;-p

Of course, your unit tests will check that the methods have been implemented, yes? ;-p

其实,这很可能是很容易通过仿制药测试 - 即有如下形式的通用测试方法:

Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:

[Test]
public void TestFoo() {
  ActualTest<Foo>();
}
[Test]
public void TestBar() {
  ActualTest<Bar>();
}

static void ActualTest<T>() where T : SomeBaseClass, new() {
  T obj = new T();
  Assert.blah something involving obj
}

这篇关于我可以强制子类覆盖方法没有使它抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆