I have an object with some properties and a dictionary which holds a temporary value for each of property. The key of this dictionary is a string with the same name of the property, while the value is an object.
What I want to do is to build a save method that reads the dictionary's keys and set the corresponding property to the value found in the dictionary.
So I thought about reflection but it's not as easy as I thought.
Here's a sample class:
public class Class{
public string Property1 { get; set; }
public int Property2 { get; set; }
public Dictionary<string, object> Settings { get; set; }
public void Save()
{
foreach (string key in Settings.Keys)
{
// PSEUDOCODE
get the property called like the key
get its type
get the value of hte key in the dictionary
cast this object to the property's value
set the property to the casted object
}
}
}
The reason why I'm not posting my code is beacuse I don't understand how to do casting and similar stuff, so I wrote a little bit of pseudocode to let you understand what I'm trying to achieve.
Is there anyone that can point me to the right direction?
Here:
//Get the type
var type= this.GetType();
foreach (string key in Settings.Keys)
{
//Get the property
var property = type.GetProperty(key);
//Convert the value to the property type
var convertedValue = Convert.ChangeType(Settings[key], property.PropertyType);
property.SetValue(this, convertedValue);
}
Not tested, but it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With