2008-12-19 9 views

उत्तर

17

ठीक है, आप शायद एक 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); 
    } 
} 

ShouldSerialize{name} पैटन में मान्यता प्राप्त है, और विधि देखने के लिए कि क्रमबद्धता में संपत्ति शामिल करने के लिए कहा जाता है। एक वैकल्पिक {name}Specified पैटर्न भी है जो आपको deserializing (सेटटर के माध्यम से) चीजों का पता लगाने की अनुमति देता है:

[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 
} 
संबंधित मुद्दे