jeudi 9 février 2017

How to set properties of same name but different types in inherited classes

Vote count: 0

I may have asked the question wrongly but stick with me here.

I am making a configuration manager that has a couple of rules.. all Keys are string, but Value can be either string, int, double or bool (but shown as 0,1 integers)

I've wrote a class and some generic stuff and also overrode ToString(); method to get a nice printing pattern AND on the wrapper class I've created an operator override to get the object. Now I'm trying to create a setter for that object but I'm having some serious troubles since the type of the value doesn't match..

public class Config()
{
    public List<ConfigEntry> ConfigLines {get;set;}

    public ConfigEntry this[string key]
    {
        get
        {
            if(CfgConfig.Any(x => x.GetKey(true) == key))
            {
                return CfgConfig.Where(x => x.GetKey(true) == key).Single();
            }
            if (ProfileConfig.Any(x => x.GetKey(true) == key))
            {
                return ProfileConfig.Where(x => x.GetKey(true) == key).Single();
            }

            return null;
        }
        set
        {
            //??????????????
        }
    }

    public class ConfigEntry()
    {
        public string CommonStuff {get;set);

        public virtual string GetKey(bool tolower = false)
        {
            return null;
        }

        public override string ToString()
        {
            return CommonStuff;
        }


    public class IntValue : ConfigEntry
    {
        public string Key {get;set;}
        public int Value {get;set;}

        public override string ToString()
        {
            return $@"{Key}={Value};";
        }

        public virtual string GetKey(bool tolower = false)
        {
            if (tolower)
                return Key.ToLower();
            else
                return Key;
        }
    }
}

Now how could I configure that setter of the operator [] for this to actually work as normal, that if I type, lets say ConfigLines["anintkey"] = 5; and ConfigLines["astringkey"] = "Hello"; that both things work.. I suppose that I do need to use the <T> class here somewhere, but I haven't used templates that much and I can't figure out a way to pull this off. I do want to keep the original list as a base class and then work from that, but I have no clue how to pull this one off.

Thank you all for the help!

asked 37 secs ago

Let's block ads! (Why?)



How to set properties of same name but different types in inherited classes

Aucun commentaire:

Enregistrer un commentaire