C# Member variable overrides used by base class method

拟墨画扇 提交于 2019-11-30 21:00:29

Is there any reason you can't use a virtual property? That would provide exactly the functionality you are looking for. It just wouldn't be a field.

protected abstract string[] array { get; }

...

protected override string[] array { get { return new string[]{"...","..."}; }}

Why do you need to override the variable? Looking from your code, just setting the values would be enough, no?

Plus, static variables are tied to the class (not the instance), therefore it's not overridable on any situation.

Simply don't use new. Set the array in your subclass' constructor.

EDIT: with code:

class subclass1 : baseclass
{
    public subclass1()
    {
        array = new string[]
        {
            "class1value1",
            "class1value2",
            "class1value3",
            "class1value4"
        };
    }
}

class subclass2 : baseclass
{
    public subclass2()
    {
        array = new string[]
        {
            "class2value1",
            "class2value2",
            "class2value3",
            "class2value4"
        };
    }
}
class BaseClass
{
    public virtual string Method()
    {
        return string.Empty;
    }
}

abstract class BaseClass<T> : BaseClass where T : BaseClass<T>
{
    protected static string[] strings;

    public override string Method()
    {
        return string.Join("  ", strings);
    }
}

class Subclass1 : BaseClass<Subclass1>
{
    static Subclass1()
    {
        strings = new[] { "class1value1", "class1value2", "class1value3" };
    }
}

class Subclass2 : BaseClass<Subclass2>
{
    static Subclass2()
    {
        strings = new[] { "class2value1", "class2value2", "class2value3" };
    }
}

The important part is the generic parameter T which basically functions as an index to the string arrays.

You're trying to get polymorphic behavior from the array but you're defining it for class local behavior.

The array has to be virtual or method() in the base class will compile to always access the array in the base class - the array should also be a property not a field to do this, i.e.,

string[] _array = { ... }; /base class local values protected virtual string[] array { get { return _array; } } //makes the array property overridable

then in the subclasses, you'll need to do

string[] _array = { ... }; //subclass local values virtual string[] array { get { return _array; } } //this overrides the base class property

in order to get the desired affect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!