lundi 14 septembre 2020

Using reflection to convert a non-generic dictionary to a generic one, without the generic parameters

I'm working on custom XML serialization for this PropertyList DTD, and so far I've fully covered all the types except "dict". Some of the dicts are essentially objects like this:

<key>1</key>
<dict>
    <key>Track ID</key><integer>1</integer>
    <key>Name</key><string>Baby</string>
    <key>Artist</key><string>Justin Bieber</string>
    [...]
</dict>

Which I've already handled.

property.SetValue(obj, xmlReader.ReadElementContentAs(propertyType, null));

For arrays, I was able to use the untyped Array class (using the ArrayList class to build it), which lets one work with type variables instead of generics, and then conveniently can go straight into the SetValue method and automatically converted to the int[] or whatever other generic is in the object.

ArrayList array = new ArrayList();
do
{
    array.Add(GetDictValue(arrayReader, elementType));
}
while (arrayReader.ReadToFollowing(elementTypeName));
property.SetValue(obj, array.ToArray(elementType));

But I cannot find any such way to do this for dictionaries. Hashtable cannot convert to a generic Dictionary<TKey, TValue> without the generic parameters.





Aucun commentaire:

Enregistrer un commentaire