jeudi 31 mars 2016

How to merge base class dataset with derived class dataset

In my project I have hierarchy of classes which implements custom properties. Here is simplified version for the console application.

class Program
{
    static void Main(string[] args)
    {
        BaseClass base_ = new BaseClass();
        DerivedClass derived_ = new DerivedClass();

        Console.WriteLine(base_.ToString());
        Console.WriteLine(derived_.ToString());


        Console.ReadLine();
    }
}

class Property
{
    string key;
    string value;

    public Property(string key, string value)
    {
        this.key = key;
        this.value = value;
    }

    public override string ToString()
    {
        return "(key=" + key + ": value=" + value + ")";
    }
}

public struct PropertyConfig
{
    public string key;
    public string defaultValue;
}

class BaseClass
{
    Dictionary<string, Property> properties = new Dictionary<string, Property>();

    protected virtual PropertyConfig[] classPropertyConfig
    {
        get
        {
            return new PropertyConfig[]
              {
                new PropertyConfig() { key = "p1",  defaultValue = "v1" },
                new PropertyConfig() { key = "p2",  defaultValue = "v2" }
              };
        }
    }

    public BaseClass()
    {
        initProperties(classPropertyConfig);
    }

    void initProperties(PropertyConfig[] configs)
    {
        foreach (PropertyConfig config in configs)
        {
            properties.Add(config.key, new Property(config.key, config.defaultValue));
        }
    }

    public override string ToString()
    {
        return GetType().Name + ".Properties: " + string.Join(",", properties.Select(kvp => kvp.Value.ToString()).ToArray());
    }
}

class DerivedClass : BaseClass
{

    protected override PropertyConfig[] classPropertyConfig
    {
        get
        {
            return new PropertyConfig[]
              {
                new PropertyConfig() { key = "p2",  defaultValue = "update" },
                new PropertyConfig() { key = "p3",  defaultValue = "v3" }
              };
        }
    }

    public DerivedClass(): base()
    {

    }
}

Base class defines a configuration of its property objects in the array which is overridden in the derived class.

the resulting output is below and it is correct. But it is not what I need.

BaseClass.Properties: (key=p1: value=v1),(key=p2: value=v2)
DerivedClass.Properties: (key=p2: value=update),(key=p3: value=v3)

What I need basically to be able to merge configs from base and derived classes in order to get this

BaseClass.Properties: (key=p1: value=v1),(key=p2: value=v2)
DerivedClass.Properties: (key=p1: value=v1), (key=p2: value=update),(key=p3: value=v3)

Ideal solution must allow to set just configuration in the derived class and nothing more.

Aucun commentaire:

Enregistrer un commentaire