lundi 21 septembre 2015

Serialize Base Class Implementation for all "new" Properties

I have a bunch of classes that were auto-generated from an XSD, and provided to me in a compiled DLL for which I don't have the source code. I have a need to add interfaces to each of the types, which resulted in code such as the following:

public interface IBar
{
    string SomeProperty { get; set; }
}

public interface IFoo<TBar> where TBar : IBar
{
    TBar Bar { get; set; }
}

[XmlType(Namespace = "SomeNamespace", TypeName = "bar")]
public class BarWrapper : BarFromXSD, IBar
{
}

[XmlType(Namespace = "SomeNamespace", TypeName = "foo")]
public class FooWrapper : FooFromXSD, IFoo<BarWrapper>
{
    [XmlElement("bar")]
    public new BarWrapper Bar
    {
        get { return base.Bar as BarWrapper; }
        set { base.Bar = value; }
    }
}

If the client gives me a DLL where any of the interfaces to the underlying types changes, I will get compile-time errors telling me such. However, that is NOT true if the serialization attributes change in the underlying DLL. In that case, my wrapper classes will happily serialize into objects that are incompatible with the associated XSDs.

To avoid this issue, I would like to do the simpler of either:

1) Override default serialization, in order to ignore the "new" property implementations, or
2) Reflectively copy all XML serialization attributes from the base class to the derived class

The issues that I am trying to address with any potential solution are:

1) I would like to perform reflection once, in the static constructor, to determine the serialized element/attribute names and namespaces.
2) I have multiple classes that follow the same pattern as FooWrapper, so any solution should would work for any such classes.
3) The classes that follow the FooWrapper pattern can contain other properties not defined in the base class that require serialization.
4) The ideal solution should gracefully handle new properties. For example, if at a later time I add or remove a "new" property, I shouldn't have to add/remove other methods, or have to hard-code the name of the "new" property in the static constructor.

Any insight to a solution that meets these requirements is greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire