问题描述
在 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).
推荐答案
如果你想覆盖它,它不是一个常量;).尝试虚拟只读属性(或受保护的 setter).
It's not a constant if you want to override it ;). Try a virtual read-only property (or protected setter).
只读属性:
public class MyClass {
public virtual string MyConst { get { return "SOMETHING"; } }
}
...
public class MyDerived : MyClass {
public override string MyConst { get { return "SOMETHINGELSE"; } }
}
受保护的设置器:
public class MyClass {
public string MyConst { get; protected set; }
public MyClass() {
MyConst = "SOMETHING";
}
}
public class MyDerived : MyClass {
public MyDerived() {
MyConst = "SOMETHING ELSE";
}
}
这篇关于覆盖 C# 派生类中的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!