简体   繁体   English

如何在C#中使用抽象和重写常量?

[英]How to have abstract and overriding constants in C#?

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! 一如既往地感谢您的帮助!

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: 您可以在基类中创建一个抽象属性(如果需要默认值,则为虚拟属性):

public abstract string Bank { get; }

Then override with: 然后覆盖:

public override string Bank { get { return "Some bank"; } }

What you are trying to do cannot be done. 你要做的事情是做不到的。 static and const cannot be overridden. staticconst不能被覆盖。 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: 您可以将该bank字段转换为属性并将其作为抽象方式进行营销,如下所示:

public abstract string Bank { get; }

Then you will override it in your inherited class like you have been doing 然后你将像你一直在继承的类中覆盖它

public override string Bank { get { return "Charter One"; } }

Hope this helps you. 希望这对你有所帮助。 On the flip side you can also do 另一方面,您也可以这样做

public const string Bank = "???";

and then on the inherited class 然后继承类

public const string Bank = "Charter One";

Since static and const operate outside of polymorphism they don't need to be overriden. 由于staticconst在多态性之外运行,因此不需要重写它们。

In case you want to keep using "const", a slight modificaiton to the above: 如果你想继续使用“const”,稍微修改一下上面的内容:

public abstract string Bank { get; } 

Then override with: 然后覆盖:

private const string bank = "Some Bank"; 
public override string Bank { get { return bank;} }  

And the property will then return your "const" from the derived type. 然后属性将从派生类型返回“const”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM