在 C# 中重写派生类中的常量
在 C# 中,可以在派生类中重写常量吗? 我有一组类,除了一些常量值之外都是相同的,因此我想创建一个定义所有方法的基类,然后在派生类中设置相关常量。 这可能吗?
我不想只是将这些值传递给每个对象的构造函数,因为我希望增加多个类的类型安全性(因为对于具有不同常量的两个对象进行交互是没有意义的)。
In C# can a constant be overridden in a derived class? I have a group of classes that are all the same bar some constant values, so I'd like to create a base class that defines all the methods and then just set the relevant constants in the derived classes. Is this possible?
I'd rather not just pass in these values to each object's constructor as I would like the added type-safety of multiple classes (since it never makes sense for two objects with different constants to interact).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你想覆盖它,它就不是一个常量;)。 尝试虚拟只读属性(或受保护的设置器)。
只读属性:
受保护的设置器:
It's not a constant if you want to override it ;). Try a virtual read-only property (or protected setter).
Read-only property:
Protected setter:
不幸的是,常量不能被覆盖,因为它们不是虚拟成员。 代码中的常量标识符在编译时由编译器替换为其文字值。
我建议您尝试使用抽象或虚拟财产来完成您想做的事情。 它们是虚拟的,因此可以(在抽象属性的情况下)在派生类型中被重写。
Unfortunately constants cannot be overridden as they are not virtual members. Constant identifiers in your code are replaced with their literal values by the compiler at compile time.
I would suggest you try to use an abstract or virtual property for what you would like to do. Those are virtual and as such can (must, in the case of an abstract property) be overridden in the derived type.
用
const
标记的常量不能被覆盖,因为它们在编译时被编译器替换。但是分配给常量值的常规静态字段可以。 我刚才遇到过这样的情况:
如果我只是在派生类中重新定义 MaxFactCell 字段,多态性将不起作用:代码使用 Columns2 为
列
将看不到覆盖值。如果您需要限制对该字段的写入(但不读取)访问,则使用
readonly
将禁止在Columns2
中重新定义它。 让它成为一个属性,这会稍微多一些代码:Constants marked with
const
cannot be overridden as they are substituted by the compiler at compile time.But regular static fields assigned to constant values can. I've had such a case just now:
If I just redefined the
MaxFactCell
field in the derived class instead, polymorphism wouldn't work: code usingColumns2
asColumns
would not see the overriding value.If you need to restrict write (but not read) access to the field, using
readonly
would prohibit redefining it inColumns2
. Make it a property instead, that's slightly more code:编辑:这可能会产生意想不到的行为,请参阅下面 Shai Petel 的评论。
您可以通过声明新常量
new
来隐藏派生类中继承的常量。 不过,我不确定这是否是一个好的做法。Edit: This can have unexpected behaviour, see Shai Petel's remark below.
You can hide the inherited constant in a derived class by declaring the new constant
new
. I'm not sure this is a good practice, though.解决 dten + Tracker1 的答案,但针对 c# 6 进行了更新
to Work off dten + Tracker1's answer but updated for c# 6
您可以强制派生类具有常量值(也就是只读属性)
例子:
You can force derived classes to have a value for a constant (well, a read-only property)
Example: