سؤال

I have an existing codebase that persists a couple of simple classes to disk via NetDataContractSerializer, but the classes are unfortunately not adorned with [DataContract], but rather with [Serializable]. This works fine, but now I want to add a few new properties to the persisted classes, while still be able to read the files generated by the old version.

Let's say this is the class:

[Serializable]
public class Persisted
{
    public int OldProperty {get;set;}
    public int NewProperty {get;set;}
}

Now, when I deserialize the old files, I get an exception because they don't contain NewProperty. This makes sense. So I wanted to have NewProperty ignored, but while there's a [OptionalField] attribute to have the serializer ignore the missing field, it can't be applied to properties - only fields.

So I figured I'll use [DataContract] and [DataMember], which also has an IsRequired property, but this changes the layout of the serialized file, and it can't read the old data files. Moreover, you can't mix [Serializable] and [DataMember] - if the serializer sees the [Serializable] attribute, it ignores the [DataMember] directives.

So, barring the option to do a one-time conversion of the old files (possible, but not my first choice), is there a way to get the NetDataContractSerializer to ignore a field in an existing XML serialized object?

هل كانت مفيدة؟

المحلول

The problem is that when using the Serializable attribute, what gets serialized are fields, not properties. Since you're using auto-properties, the fields are hidden and you can't add attributes to them.

The solution is simple - don't use auto-properties.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top