I have a base class, SpecialClass. Lots of other classes inherit from it, like WriteSpecialClass and ReadSpecialClass. Instances of these classes are serialized and deserialized, after being casted to/from the base class. Therefore, I have lots of repetitious code like this (for serializing):
SpecialClass sc = null;
if (type.DisplayName == "Read") {
sc = new ReadSpecialClass();
} else if (type.DisplayName == "Write") {
sc = new WriteSpecialClass();
} else
throw new NotSupportedException("Type not supported");
String xml = SerializeToXML(sc);
.. and deserializing:
SpecialClass sc = null;
sc = (SpecialClass)DeserializeFromXML(xml);
switch (someVariableThatDicatesTypeOfSpecialClass) {
case "Read":
sc = (ReadSpecialClass)sc;
break;
case "Write":
sc = (WriteSpecialClass)sc;
break;
}
One more important piece of info: SpecialClass has a bunch of abstract methods defined which each class that inherits from it needs to implement. All the classes which inherit from it conform to the methods, but return different things, so each class is not the same.
I can post my serialization or deserialization methods if needed.
I would like to try and simplify this so that I don’t have to specify each SpecialClass-derived class (like ReadSpecialClass). Is there any way to do this? The only way I can think of is duck-typing. Thanks for your help,
For serializing, you can use some sort of lookup:
For deserialization, these two lines:
perform no actual conversion. The only thing they will do is throw an exception if the object referenced by
scis not of the appropriate type. What you are doing here is roughly the same thing as:Sure, the cast will succeed. But it does not in any way modify the object pointed to by
a. All it really does is verify that this object is already a string.