XML Serialize / Deserialize generic dictionary holding various generic types
-
Hi, I'm kind of stuck with an serializing / deserializing problem using a generic dictionary holding references to various generic types. It goes as follows:
class MyBase : IXmlSerializable { // whatever } class MyGeneric : MyBase, IXmlSerializable { MyGeneric(Valuetype tVal) { val = tVal; } ValueType val; } class Program { dictionary m_Dic = new dictionary(); void FillDictionary() { dictionary.Add("Key1", new MyGeneric(10)); dictionary.Add("Key1", new MyGeneric("StringValue")); dictionary.Add("Key1", new MyGeneric(3.1415)); } }
Ok, I hope you can see the idea behind it. It's mainly thought to hold a variety of different types whithout specifying a parameter enum which selects the appropiate value via a huge switch statement on lots of overloads to the value Get/Set property. While I'm able to serialize the dictionary without a problem to an XML file, I'm stuck deserializing it. The problem: how can I can generate a generic from a textinformation like or MyApp.MyGeneric`1[System.String] ? The first classification is generated by the .Net serializer and the second is generated from typeof(...) . Any ideas are very appreciated. Thanks, Florian -
Hi, I'm kind of stuck with an serializing / deserializing problem using a generic dictionary holding references to various generic types. It goes as follows:
class MyBase : IXmlSerializable { // whatever } class MyGeneric : MyBase, IXmlSerializable { MyGeneric(Valuetype tVal) { val = tVal; } ValueType val; } class Program { dictionary m_Dic = new dictionary(); void FillDictionary() { dictionary.Add("Key1", new MyGeneric(10)); dictionary.Add("Key1", new MyGeneric("StringValue")); dictionary.Add("Key1", new MyGeneric(3.1415)); } }
Ok, I hope you can see the idea behind it. It's mainly thought to hold a variety of different types whithout specifying a parameter enum which selects the appropiate value via a huge switch statement on lots of overloads to the value Get/Set property. While I'm able to serialize the dictionary without a problem to an XML file, I'm stuck deserializing it. The problem: how can I can generate a generic from a textinformation like or MyApp.MyGeneric`1[System.String] ? The first classification is generated by the .Net serializer and the second is generated from typeof(...) . Any ideas are very appreciated. Thanks, FlorianFor the interested ones, I found a solution:
Type t = Type.GetType(typestring); object o = Activator.CreateInstance(t);
This works, if you serialize the type on saving with GetType().ToString().