2016-03-01 102 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