Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Object graphs can be used with DataContract serialization.</p> <p><strong>Note:</strong> Make sure you're preserving object references, so that you don't end up with multiple copies of the same object in the graph when they should all be the same reference, the default behavior does not preserve identity like this.</p> <p>This can be done by specifying the <code>preserveObjectReferences</code> parameter when constructing a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx" rel="nofollow noreferrer">DataContractSerializer</a> or by specifying <code>true</code> for the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.isreference(v=VS.90).aspx" rel="nofollow noreferrer">IsReference</a> property on <code>DataContractAttribute</code> (this last attribute requires .NET <strong>3.5SP1</strong>).</p> <p>However, when sending object graphs over WCF, you have the risk of running afoul of WCF quotas (and there are many) if you don't take care to ensure the graph is kept to a reasonable size.</p> <p>For the <code>net.tcp</code> transport, for example, important ones to set are <code>maxReceivedMessageSize</code>, <code>maxStringContentLength</code>, and <code>maxArrayLength</code>. Not to mention a hidden quota of 65335 distinct objects allowed in a graph (<code>maxObjectsInGraph</code>), that can only be overridden with difficulty.</p> <p>You can also use classes that only expose read accessors with the <code>DataContractSerializer</code>, and have no parameterless constructors:</p> <pre><code>using System; using System.IO; using System.Runtime.Serialization; class DataContractTest { static void Main(string[] args) { var serializer = new DataContractSerializer(typeof(NoParameterLessConstructor)); var obj1 = new NoParameterLessConstructor("Name", 1); var ms = new MemoryStream(); serializer.WriteObject(ms, obj1); ms.Seek(0, SeekOrigin.Begin); var obj2 = (NoParameterLessConstructor)serializer.ReadObject(ms); Console.WriteLine("obj2.Name: {0}", obj2.Name); Console.WriteLine("obj2.Version: {0}", obj2.Version); } [DataContract] class NoParameterLessConstructor { public NoParameterLessConstructor(string name, int version) { Name = name; Version = version; } [DataMember] public string Name { get; private set; } [DataMember] public int Version { get; private set; } } } </code></pre> <p>This works because <code>DataContractSerializer</code> can instantiate types without calling the constructor.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload