2008-12-19 16 views

Respuesta

17

Bueno, tal vez podría agregar un método ShouldSerializeFoo():

using System; 
using System.ComponentModel; 
using System.Xml.Serialization; 
[Serializable] 
public class MyEntity 
{ 
    public string Key { get; set; } 

    public string[] Items { get; set; } 

    [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] 
    public bool ShouldSerializeItems() 
    { 
     return Items != null && Items.Length > 0; 
    } 
} 

static class Program 
{ 
    static void Main() 
    { 
     MyEntity obj = new MyEntity { Key = "abc", Items = new string[0] }; 
     XmlSerializer ser = new XmlSerializer(typeof(MyEntity)); 
     ser.Serialize(Console.Out, obj); 
    } 
} 

Se reconoce el Patten ShouldSerialize{name}, y el método se llama para ver si se debe incluir el establecimiento con la serialización. También hay un patrón alternativo {name}Specified que también le permite detectar cosas cuando deserializa (a través del colocador):

[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] 
[XmlIgnore] 
public bool ItemsSpecified 
{ 
    get { return Items != null && Items.Length > 0; } 
    set { } // could set the default array here if we want 
} 
Cuestiones relacionadas