I'm trying to 'serialize' a certain type by iterating through its properties and write down every value type into a dictionary.
Pseudo
serialize(object)
foreach(prop in object.GetType().GetProperties()
value = prop.GetValue(object);
if (prop.PropertyType.isValueType)
writeToDict(prop.Name, value)
else
serialize(value)
given a certain type
public class ComplexType {
public string Prop1 { get; set; }
public int Prop2 { get; set; }
public OtherType Prop3 { get; set; }
}
public class OtherType {
public string Prop4 { get; set; }
}
Now, when I create an instance of ComplexType
and try to 'serialize' it, it works fine until it iterates over Prop3
(OtherType
). When I try to call value.GetType()
on it, I run into a NullReferenceException
because, of course, there has never been a reference set to Prop3
.
Is there any way to work around this? How do other serialization frameworks do this? (I mean, I can't even create a default instance of that type because I don't know the type at runtime!)
Oh, and yes, I can't skip the property because I'm interested in the structure (even if it doesn't have a value set).
Aucun commentaire:
Enregistrer un commentaire