Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would suggest something like the following. This code could be improved by adding support for detecting intermediate class hierarchy types that don't have a dispatch mapping and calling the nearest dispatch method based on the runtime hierarchy. It could also be improved by using reflection to detect overload of ExecuteInteral() and adding them automatically to the dispatch map.</p> <pre><code>using System; using System.Collections.Generic; namespace LanguageTests2 { public class A { } public class B : A {} public class C : B {} public static class VirtualExtensionMethods { private static readonly IDictionary&lt;Type,Action&lt;A&gt;&gt; _dispatchMap = new Dictionary&lt;Type, Action&lt;A&gt;&gt;(); static VirtualExtensionMethods() { _dispatchMap[typeof(A)] = x =&gt; ExecuteInternal( (A)x ); _dispatchMap[typeof(B)] = x =&gt; ExecuteInternal( (B)x ); _dispatchMap[typeof(C)] = x =&gt; ExecuteInternal( (C)x ); } public static void Execute( this A instance ) { _dispatchMap[instance.GetType()]( instance ); } private static void ExecuteInternal( A instance ) { Console.WriteLine("\nCalled ToString() on: " + instance); } private static void ExecuteInternal(B instance) { Console.WriteLine( "\nCalled ToString() on: " + instance ); } private static void ExecuteInternal(C instance) { Console.WriteLine("\nCalled ToString() on: " + instance); } } public class VirtualExtensionsTest { public static void Main() { var instanceA = new A(); var instanceB = new B(); var instanceC = new C(); instanceA.Execute(); instanceB.Execute(); instanceC.Execute(); } } } </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