Reputation: 980
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 TextValue : ConfigEntry
{
public string Key {get;set;}
public string 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;
}
}
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!
Upvotes: 0
Views: 482
Reputation: 489
You can make ConfigEntry<T>
, but then you will be forced to make Config<T>
which contains List<ConfigEntry<T>>
. So that isn't solution.
All you need is just dynamic
:
var conf = new Dictionary<string, dynamic>();
conf["url"] = "http://example.com";
conf["timeout"] = 30;
// in some other place
string url = conf["url"];
int timeout = conf["timeout"];
Upvotes: 1