不同之处在于生成的xml结构的不同.
MessageHeader应用于数组属性时,会把数组元素包装在一个节点内,而使用MessageHeaderArray时,就不会有个包装节点.
比如 string[] Messages 属性,使用MessageHeader,则序列化出来的xml为:
<messages>
<string> xxxxxxxx</string>
<string> xxxxxxxx</string>
<string> xxxxxxxx</string>
</messages>
使用MessageHeaderArray时,则为:
<messages> xxxxxxxx</messages>
<messages> xxxxxxxx</messages>
<messages> xxxxxxxx</messages>
你可以自己使用XmlSerialize序列化化 List<T> 和 T[] 来观察输出的xml文件的不同,和上面是一样的.
namespace CSAppConsole {
[MessageContract]
public class WrapperArray {
[MessageHeader]
public int Index { get; set; }
[MessageHeader]
public string[] StringArray { get; set; }
}
[MessageContract]
public class UnwrapperArray {
[MessageHeader]
public int Index { get; set; }
[MessageHeaderArray]
public string[] StringArray { get; set; }
}
class Program {
static void Main(string[] args) {
DataContractSerializer serilaizer = new DataContractSerializer(typeof(WrapperArray));
using (MemoryStream ms = new MemoryStream()) {
WrapperArray wrapper = new WrapperArray {
Index = 1,
StringArray = new string[] { "string1", "string2", "string3" }
};
serilaizer.WriteObject(ms, wrapper);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms)) {
Console.WriteLine(sr.ReadToEnd());
}
}
serilaizer = new DataContractSerializer(typeof(UnwrapperArray));
using (MemoryStream ms = new MemoryStream()) {
UnwrapperArray wrapper = new UnwrapperArray {
Index = 1,
StringArray = new string[] { "string1", "string2", "string3" }
};
serilaizer.WriteObject(ms, wrapper);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms)) {
Console.WriteLine(sr.ReadToEnd());
}
}
Console.Read();
}
}
}