Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here are two C# solutions, one basically is the same but more neat and is good when you have small number of child classes.</p> <pre><code>public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Action { private static Dictionary&lt;Type, Action&lt;Parent&gt;&gt; _d = new Dictionary&lt;Type, Action&lt;Parent&gt;&gt;() { {typeof(Child1), p=&gt;action((Child1)p)}, {typeof(Child2), p=&gt;action((Child2)p)}, {typeof(Parent), p=&gt;action(p)} }; public static void perform(Parent p) { _d[p.GetType()](p); } private static void action(Parent p) { } private static void action(Child1 c1) { } private static void action(Child2 c2) { } } class Program { static void Main(string[] args) { Parent p = new Child1(); Action.perform(p); } }`enter code here` </code></pre> <p>Anyhow it breaks OCP but is faster than using reflection. This one does not break OCP but uses reflection to fill the dictionary:</p> <pre><code>public class Action { private static Dictionary&lt;Type, Action&lt;Parent&gt;&gt; _d; static Action() { Initialize(); } private static void Initialize() { var methods = typeof(Action) .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(IsActionMethod) .ToList(); _d = methods.ToDictionary(m =&gt; m.GetParameters().First().ParameterType, m =&gt; (Action&lt;Parent&gt;) (x =&gt; m.Invoke(null, new[] {x}))); } private static bool IsActionMethod(MethodInfo methodInfo) { var parameters = methodInfo.GetParameters(); return parameters.Length == 1 &amp;&amp; typeof(Parent).IsAssignableFrom(parameters.First().ParameterType) &amp;&amp; methodInfo.ReturnType == typeof(void); } public static void perform(Parent p) { _d[p.GetType()](p); } private static void action(Parent p) { } private static void action(Child1 c1) { } private static void action(Child2 c2) { } } </code></pre>
    singulars
    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.
 

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