XmlSerializer and factory -created elements

I am trying to serialize / deserialize objects with factory-created members. For example, suppose there is a member of a type Foothat is created using FooFactory.CreateFoo (int bar).

My current idea is

1. create a custom XmlReader (for example, get from XmlTextReader) and attach a factory to it

2.implement IXmlSerializable

3.in ReadXml (), I can grab the factory from the reader.

Not sure if this is the most elegant way to do this, has anyone made such an attempt?

+5
source share
1 answer

XmlSerializer . , XmlSerializer, DTO first . DTO factory , . DTO ; XmlSerializer, .

, IXmlSerializable - , : API 100% ( , xml). , API , . , DTO ( ), IXmlSerializable.

, :

[XmlRoot("foo")]
public class FooDTO {
     [XmlAttribute("bar")]
     public int Bar {get;set;}

     public static implicit operator Foo(FooDTO value)
     {
         return value == null ? null : FooFactory.Create(value.Bar);
     }
     public static implicit operator FooDTO(Foo value)
     {
         return value == null ? null : new FooDTO { Bar = value.Bar; }
     }
}

Foo FooDTO :

Foo foo = ...
FooDTO dto = foo;
+5

All Articles