C# 中的覆盖常量

  • 本文关键字:常量 覆盖 c#
  • 更新时间 :
  • 英文 :


我在 c# 中有这样的类:

public class Foo 
{
    public static readonly int SIZE = 2;
    private int[] array;
    public Foo
    {
        array = new int[SIZE];
    }
}

Bar类:

public class Bar : Foo
{
    public static readonly int SIZE = 4;
}

我想做的是创建一个 Bar 实例,其数组大小取自被覆盖的 SIZE 值。如何正确操作?

你不能

这样做。您可以使用虚拟方法:

public class Foo 
{
    protected virtual int GetSize(){return 2;};
    private int[] array;
    public Foo
    {
        array = new int[GetSize()];
    }
}

也可以使用反射来查找静态场SIZE,但我不建议这样做。

您的 SIZE 常量是静态的

,静态字段不是继承的 - Foo.SIZE 和 Bar.SIZE 是两个彼此无关的不同常量。这就是为什么 Foo 的构造函数调用将始终初始化为 2,而不是 4。

你可以做的是在Foo中创建一个protected virtual void Initialize()方法,用2初始化数组,并在Bar中覆盖它以用4初始化它。

不能继承静态字段;请改用以下内容:

public class Foo
{
    protected virtual int SIZE
    {
        get
        {
            return 2;
        }
    }
    private int[] array;
    public Foo()
    {
        array = new int[SIZE];
    }
}
public class Bar : Foo
{
    protected override int SIZE
    {
        get
        {
            return 4;
        }
    }
}

Virtual 就像说"这是基类的默认值";而 Override 会更改实现 "Foo" 的类的值。

最新更新