Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use <a href="http://msdn.microsoft.com/en-us/library/ee207183.aspx" rel="nofollow">covariance</a>. Since variant type parameters only can be declared in interfaces and delegates (not in class definitions), you also need to define an interface:</p> <pre><code>public interface IGenericObject&lt;out T&gt; { string Key { get; } T Value { get; } } public abstract class GenericObject&lt;T&gt; : IGenericObject&lt;T&gt; { public string Key { get; set; } public T Value { get; set; } protected GenericObject() { } protected GenericObject(string key, T value) : this() { this.Key = key; this.Value = value; } } public class GenericList&lt;TGenericObject&gt; : IXmlSerializable where TGenericObject : IGenericObject&lt;object&gt; { private readonly List&lt;TGenericObject&gt; _list = new List&lt;TGenericObject&gt;(); public void Add(TGenericObject item) { _list.Add(item); } public XmlSchema GetSchema() { // ... } public void ReadXml(XmlReader reader) { // ... } public void WriteXml(XmlWriter writer) { // ... } } public class Person : GenericObject&lt;string&gt; { } </code></pre> <p>Now you can do this:</p> <pre><code>public class SomeClass { public void SomeMethod() { Person somePerson = new Person(); GenericList&lt;IGenericObject&lt;object&gt;&gt; listWithGenericsOfObject = new GenericList&lt;IGenericObject&lt;object&gt;&gt;(); listWithGenericsOfObject.Add(somePerson); GenericList&lt;IGenericObject&lt;string&gt;&gt; listWithGenericsOfString = new GenericList&lt;IGenericObject&lt;string&gt;&gt;(); listWithGenericsOfString.Add(somePerson); GenericList&lt;Person&gt; listWithGenericsOfPerson = new GenericList&lt;Person&gt;(); listWithGenericsOfPerson.Add(somePerson); } } </code></pre> <p>Now you don't need to check the type at runtime using IsAssignableFrom. However, in case you will need it, you should swap the types like this:</p> <pre><code>typeof(GenericObject&lt;object&gt;).IsAssignableFrom(typeof(T)) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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