ものがたり(旧)

atsushieno.hatenablog.com に続く

huh? in IgnoreDataMemberAttribute

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx


The data contract model is an "opt-in" model. Applying the DataMemberAttribute to a field or property explicitly specifies that the member value will be serialized. In contrast, the BinaryFormatter serializes public and private fields of a type, and the XmlSerializer serializes only public fields and properties of a type. (下線筆者)

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ignoredatamemberattribute.aspx


Apply the IgnoreDataMemberAttribute attribute to opt-out of the default DataContractSerializer behavior. By default, the DataContractSerializer serializes all publicly visible types. All public read/write properties and fields of the type are serialized. You can change the default behavior by applying the DataContractAttribute and DataMemberAttribute attributes to the types and members. (下線筆者)

( ゚д゚)ポカーン

…いや、どう見ても前者が正しいです。本当にありがとうございました。


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

[DataContract]
public class Wrapper
{
[DataMember (Order = 1)]
public Test T;

[DataMember (Order = 2)]
public Test T2;
}

[DataContract]
public class Test
{
[DataMember]
public string F = "x";

public static void Main ()
{
string ns = "http://schemas.microsoft.com/2003/10/Serialization/";
var dc = new DataContractSerializer (typeof (Wrapper));
Test t = new Test ();
using (var xw = XmlWriter.Create (Console.Out)) {
xw.WriteStartElement ("z", "root", ns);
dc.WriteObject (xw, new Wrapper () {T = t, T2 = t});
xw.WriteEndElement ();
}
}
}


<?xml version="1.0" encoding="shift_jis"?><z:root xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"><Wrapper xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/"><T><F>x</T><T2><F>x</F></T2></Wrapper></z:root>