2016-03-01 106 views
0

我有幾個屬性的類。這些屬性的價值將根據特定條件分配。在將這些值分配給幾個屬性之後,我想序列化該對象並僅包含那些賦予它們值的道具。c中屬性的條件序列化#

我試過在互聯網上搜索這個,但我找不到任何運氣。

任何有關實施此建議將不勝感激。

更新:

我有一些類,如

class A{ 
     public static string PropA_in_A { get; set; } 
     public string PropB_in_A { get; set; } 
     public static string PropC_in_A { get; set; } 
     public static string PropD_in_A { get; set; } 
} 

class B{ 
     public static string PropA_in_B { get; set; } 
     public static string PropB_in_B { get; set; } 
     public static string PropC_in_B { get; set; } 
     public static string PropD_in_B { get; set; } 
} 

class C{ 
     public static string PropA_in_C { get; set; } 
     public static string PropB_in_C { get; set; } 
     public static string PropC_in_C { get; set; } 
     public static string PropD_in_C { get; set; } 
} 

值的屬性在這些類需要分配基礎條件。 賦值之後,只有那些需要序列化的屬性才能賦值給它們。

main() 
{ 
A.PropB_in_A="Some Value"; 
A.PropA_in_B="Some Value"; 
A.PropC_in_C="Some Value"; 
} 

在這裏,我想序列化只有那些屬性賦值給他們。

+0

的可能的複製[XML序列化 - 隱藏空值(http://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values ) –

回答

0

您可以在每個屬性上使用XmlElementAttribute,並將IsNullable設置爲false。

在MSDN here上有一個示例。

[XmlElementAttribute(IsNullable = false)] 
public string City; 

或者用簡短形式:

[XmlElement(IsNullable = false)] 
public string City; 

編輯:對於空值類型,你必須通過一些額外的跳火圈,並添加屬性告訴序列是否應該序列化值。

public bool ShouldSerializeMyNullableInt() 
{ 
    return MyNullableInt.HasValue; 
} 

看到這個答案以供參考:Xml serialization - Hide null values