如何在 C# 中拥有抽象常量和重写常量?
我下面的代码无法编译。我做错了什么?我基本上试图拥有一个在基类中被重写的公共常量。
public abstract class MyBaseClass
{
public abstract const string bank = "???";
}
public class SomeBankClass : MyBaseClass
{
public override const string bank = "Some Bank";
}
一如既往地感谢您的帮助!
My code below won't compile. What am i doing wrong? I'm basically trying to have a public constant that is overridden in the base class.
public abstract class MyBaseClass
{
public abstract const string bank = "???";
}
public class SomeBankClass : MyBaseClass
{
public override const string bank = "Some Bank";
}
Thanks as always for being so helpful!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想继续使用“const”,请对上面的内容稍作修改:
然后用以下内容覆盖:
然后该属性将从派生类型返回您的“const”。
In case you want to keep using "const", a slight modificaiton to the above:
Then override with:
And the property will then return your "const" from the derived type.
如果你的常量描述你的对象,那么它应该是一个属性。顾名思义,常量不应改变,并且被设计为不受多态性的影响。这同样适用于静态变量。
您可以在基类中创建一个抽象属性(如果需要默认值,则创建虚拟属性):
然后使用以下内容覆盖:
If your constant is describing your object, then it should be a property. A constant, by its name, should not change and was designed to be unaffected by polymorphism. The same apply for static variable.
You can create an abstract property (or virtual if you want a default value) in your base class:
Then override with:
你想做的事无法完成。
static
和const
无法被覆盖。只能覆盖实例属性和方法。您可以将该
bank
字段转换为属性并将其作为抽象市场,如下所示:然后您将在继承的类中重写它,就像您一直在做的
那样希望这对您有帮助。另一方面,您也可以
在继承的类上执行此
操作,因为
static
和const
在多态性之外进行操作,因此不需要覆盖它们。What you are trying to do cannot be done.
static
andconst
cannot be overridden. Only instance properties and methods can be overridden.You can turn that
bank
field in to a property and market it as abstract like the following:Then you will override it in your inherited class like you have been doing
Hope this helps you. On the flip side you can also do
and then on the inherited class
Since
static
andconst
operate outside of polymorphism they don't need to be overriden.