Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>By adding an intermediate class and a dictionary, <strong>specialization is possible</strong>.</p> <p>To specialize on T, we create an generic interface, having a method called (e.g.) Apply. For the specific classes that interface is implemented, defining the method Apply specific for that class. This intermediate class is called the traits class.</p> <p>That traits class can be specified as a parameter in the call of the generic method, which then (of course) always takes the right implementation.</p> <p>Instead of specifying it manually, the traits class can also be stored in a global <code>IDictionary&lt;System.Type, object&gt;</code>. It can then be looked up and voila, you have real specialization there.</p> <p>If convenient you can expose it in an extension method.</p> <pre><code>class MyClass&lt;T&gt; { public string Foo() { return "MyClass"; } } interface BaseTraits&lt;T&gt; { string Apply(T cls); } class IntTraits : BaseTraits&lt;MyClass&lt;int&gt;&gt; { public string Apply(MyClass&lt;int&gt; cls) { return cls.Foo() + " i"; } } class DoubleTraits : BaseTraits&lt;MyClass&lt;double&gt;&gt; { public string Apply(MyClass&lt;double&gt; cls) { return cls.Foo() + " d"; } } // Somewhere in a (static) class: public static IDictionary&lt;Type, object&gt; register; register = new Dictionary&lt;Type, object&gt;(); register[typeof(MyClass&lt;int&gt;)] = new IntTraits(); register[typeof(MyClass&lt;double&gt;)] = new DoubleTraits(); public static string Bar&lt;T&gt;(this T obj) { BaseTraits&lt;T&gt; traits = register[typeof(T)] as BaseTraits&lt;T&gt;; return traits.Apply(obj); } var cls1 = new MyClass&lt;int&gt;(); var cls2 = new MyClass&lt;double&gt;(); string id = cls1.Bar(); string dd = cls2.Bar(); </code></pre> <p>See this <a href="http://barendgehrels.blogspot.com/2010/07/c-specializations-by-traits-i.html" rel="noreferrer">link</a> to my recent blog and the follow ups for an extensive description and samples.</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