Note that there are some explanatory texts on larger screens.

plurals
  1. POserialize list of generic type
    text
    copied!<p>I am writing an application for serialization of a generic List that holds any datatype.So I designed a base-DataType to fill the list with as follows:</p> <pre><code>public abstract class GenericObject&lt;T&gt; { public string key; public T value; public GenericObject() { } public GenericObject(string key, T value) : this() { this.key = key; this.value = value; } } </code></pre> <p>Furthermore there is a class <code>GenericList</code> which implements the <code>IXmlSerializable</code>-Interface to write a key-value pair as like this: </p> <pre><code>GenericObject&lt;int&gt; myInt = new GenericObject&lt;int&gt;("key", 3); </code></pre> <p>Which will produce the following XML: </p> <pre><code>&lt;key&gt;3&lt;/key&gt; </code></pre> <p>The class-definition for the <code>GenericList</code> is more or less as follows:</p> <pre><code>public class GenericList&lt;T&gt; : IXmlSerializable { List&lt;T&gt; objects; // ... } </code></pre> <p>So let´s assume we have a class <code>Person</code> that derives from <code>GenericObject&lt;string&gt;</code>(no matter how it looks like) and we want to fill the list with a couple of persons. The problem I have is defining a constraint on the generic type T of the <code>GenericList</code>-class so that only types are possible that derive from <code>GenericObject</code>. I already tried it by using <code>public class GenericList&lt;T&gt; : IXmlSerializable where T : GenericObject&lt;object&gt;</code> but that did not work because of the following compiler error:</p> <pre><code>Person' cannot be used as type parameter 'T' in the generic type or method 'GenericList&lt;T&gt;'. There is no implicit reference conversion from 'Person' to 'GenericObject&lt;object&gt;' </code></pre> <p>I also tried out leaving the where-clause empty, but then I have to check the type of <code>T</code> within the <code>GenericList</code> in order to get its key and value where I also failed with the following: </p> <pre><code>if (typeof(T).IsAssignableFrom(typeof(GenericObject&lt;object&gt;))) </code></pre> <p>which will always return false as <code>T</code> is of type Person and not <code>GenericObject&lt;object&gt;</code>.</p> <p>May anyone have some suggestion how I can fill my list with a person?</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