I’ve hit the problem of serializing a property for the last time. When you create a type that contains a non-serializable type, in my case a CultureInfo class, you cannot automatically serialize the type – you get issues about "does not contain a public constructor", "problem reflecting the type", etc. Unfortunately this isn’t caught at compile time and you have to wait until an attempt is made to serialize the containing object. What to do about it? The more complicated choice is to write some custom serialization code, but really, most of the time I just want to serialize pretty simple objects. So my preference is to mark the class as serializable and let the client choose how to serialize it, i.e. via Binary or Xml "serializers". The framework provides a couple of attributes for this, and this is where the gotcha lives.
The first attribute, [NonSerialized], should be applied to field members and informs the standard serialization methods to ignore the field. The second attribute, [System.Xml.Serialization.XmlIgnore], should be applied to public properties and informs the Xml Serializer to ignore the property. The combination of the two should be enough to stop the field from being serialized regardless of the serializer the client chooses to use.
Quick pseudo example:
[NonSerialized],
private SomeUnFriendlyType myType:
[System.Xml.Serialization.XmlIgnore]
public SomeUnFriendlyType MyType()
….
Like this:
Like Loading...