我可以强制子类覆盖一个方法而不使其抽象吗? [英] Can I force subclasses to override a method without making it abstract?

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

问题描述

我有一个包含一些抽象方法的类,但我希望能够在设计器中编辑该类的子类.但是,设计者不能编辑子类,除非它可以创建父类的实例.所以我的计划是用存根替换抽象方法并将它们标记为虚拟 - 但是如果我创建另一个子类,如果我忘记实现它们,我不会得到编译时错误.

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?

推荐答案

好吧,你可以做一些涉及 #if 的非常混乱的代码 - 即在 DEBUG 中它是虚拟的(对于设计者),但在 RELEASE 中它是抽象的.不过,维护起来真的很痛苦.

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.

但除此之外:基本上,没有.如果您需要设计器支持,它就不能是抽象的,因此您只能使用虚拟"(大概是基本方法抛出 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天全站免登陆