Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>JavaScriptSerializer serialization: IEnumerable -> JavaScript Array</h2> <p>When the JavaScriptSerializer is used, it automatically converts an IEnumerable (without IDictionary) type -- that covers List&lt;> or anything derived from it -- into an array.</p> <h2>Deserialization: JavaScript Array -> IEnumerable -> Collection Object</h2> <p>Now, upon <strong>deserialization</strong> from JSON, the JavaScriptSerializer must take the array, create an IEnumerable, then create an object for the field by passing that IEnumerable into its constructor. </p> <h2>Constructing Collection object via Constructor</h2> <p>Now, for List&lt;> you have a constructor overload that takes an IEnumerable. So if you put <code>List&lt;Test&gt;</code> as the type of your component it creates it fine.</p> <h2>Constructors not inherited</h2> <p>However, TestCol does <strong>NOT</strong> have such a constructor! The reason why it worked with <code>List&lt;Test&gt;</code> and not with <code>TestCol</code> (which derives from <code>List&lt;Test&gt;</code>) is that the only thing that is <strong>not</strong> inherited between classes are constructors!</p> <p>Therefore, the JavaScriptSerializer does not have any way to construct a TestCol from an IEnumerable. So it fails silently.</p> <h2>Deserialize Array by Creating List, then Casting to Type</h2> <p>Now the JavaScriptSerializer may then attempt to create a <code>List&lt;Test&gt;</code> from this <code>IEnumerable&lt;Test&gt;</code>, and then try to cast it into a TestCol.</p> <h2>Possible Solution</h2> <p>Solution: Try putting in:</p> <pre><code>public TestCol () {} // Need this when you have another constructor public TestCol (IEnumerable&lt;Test&gt; list) : base(list) {} // Constructor that takes an IEnumerable public TestCol (IList&lt;Test&gt; list) : base(list) {} // Constructor that takes an IList </code></pre> <p>as your TestCol's constructors. </p> <p>And if it still doesn't work, implement an explicit type cast from <code>List&lt;Test&gt;</code> to <code>TestCol</code>.</p> <pre><code>public static explicit operator TestCol(IList&lt;Test&gt; list) { return new TestCol(list); } </code></pre>
 

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