Using reflection, I am trying to grasp onto a class fields and populate them. Currently I have it detecting an instance of a Dictionary<,> and creating a Dictionary<object,object> to fill. Afterwards its tries to change the type, however this does not work and fails casting:
// Looping through properties. Info is this isntance.
// Check is a dictionary field.
Dictionary<object, object> newDictionary = new Dictionary<object, object>();
// Populating the dictionary here from file.
Type[] args = info.PropertyType.GetGenericArguments();
info.GetSetMethod().Invoke(data, new object[]
{
newDictionary.ToDictionary(k => Convert.ChangeType(k.Key, args[0]),
k => Convert.ChangeType(k.Value, args[1]))
});
Any ideas? Thanks.
You should create dictionary manualy of type you found.
Proof for downvoters.
Dictionary<TKey, TValue>implementsIDictionary, in my example Im creating instance ofDictionary<TKey, TValue>(Type dictionary = typeof(Dictionary<,>);).