在C#中覆盖常量

时间:2012-04-22 10:59:59

标签: 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值。怎么做得好?

3 个答案:

答案 0 :(得分:3)

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

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

    public Foo
    {
        array = new int[GetSize()];
    }
}

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

您不能继承静态字段;而是使用以下:

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;
        }
    }
}

虚拟就像是说“这是基类的默认值”;而Override更改了实现“Foo”的类的值。