我可以强制子类来声明一个常量? [英] Can I force a subclass to declare a constant?

查看:86
本文介绍了我可以强制子类来声明一个常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲迫使子类来定义的恒定值。

I want to force subclasses to define a constant value.

如同

const string SomeConstantEverySubclassMustDefine = "abc";



我需要的,因为我需要把它绑在类型,而不是实例和你不能覆盖静态方法/属性IIRC。

I need that because I need to have it tied to the Type, rather than to the instance and you can't override static Methods/Properties iirc.

我真的很想对那些常量编译时检查。

I'd really like to have a compile-time check for those constants.

让我更详细地解释:

在我们的领域,模型的几个类是特殊的,可以采取某些行动对他们来说,根据不同的类型。因此,逻辑相连的类型。要采取的行动需要绑类型的字符串。我当然可以创建一个实例每次作为一种解决方法,并声明一个抽象属性,但是这不是我想要的。我要强制在编译时字符串的声明,只是要确定。

Some classes in our Domain-Model are special, you can take certain actions for them, depending on the type. Thus the logic is tied to the type. The action to be taken requires a string tied to the type. I sure could create an instance everytime as a workaround and declare an abstract property, but that's not what I want. I want to enforce the declaration of the string at compile-time, just to be sure.

推荐答案

没有,你不能。我建议你让你的基类的抽象,与当你想,你可以获取一个抽象的财产。然后,每个子类可以只是如果想返回一个常量执行财产。缺点是,你不能在基类的静态方法中使用此 - 但那些不与子类相关反正

No, you can't. I would suggest you make your base class abstract, with an abstract property which you can fetch when you want. Each child class can then implement the property just by returning a constant if it wants. The downside is that you can't use this within static methods in the base class - but those aren't associated with the child classes anyway.

(它还允许的子类可以自定义每个实例的属性,以及,如果需要的话......但这是极少的实际问题。)

(It also allows child classes to customise the property per instance as well, if necessary... but that's rarely an actual problem.)

如果这不做够你,你可能要考虑一个平行的类型层次。基本上多态性根本没有在.NET中特定类型的方式发生;只有在一个特定实例的方式。

If this doesn't do enough for you, you might want to consider a parallel type hierarchy. Basically polymorphism simply doesn't happen in a type-specific way in .NET; only in an instance-specific way.

如果您的还是的要做到这一点,与反思取水的时候,我建议你只写单元测试以确保有关的常数的定义。当你超越了类型系统可以形容,那就是往往你能做的最好的。

If you still want to do this and fetch it with reflection, I suggest you just write unit tests to ensure that the relevant constants are defined. When you get beyond what the type system can describe, that's often the best you can do.

这篇关于我可以强制子类来声明一个常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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