c# - How do I refactor a switch-case using polymorphism? -
from console commands in format [command][position][value] e.g. multiply 2 3 , supposed manipulate array of integers according command. example if have int[] arr = new int[] { 0, 2, 0 };
after executing "multiply 2 3" command array should { 0, 8, 0 }
the way i'm doing giving info method performs manipulation.
static void performaction(int[] arr, string action, int position, int value) { switch (action) { case "multiply": array[position] *= value; break; case "add": array[pos] += value; break; case "subtract": array[pos] -= value; break; } }
my question - how apply polymorphism and/or reflection can say:
executecommand(int[] arr, string action, int position, int value)
and maybe have class each command, every command knows how executed.
a simple calculator using reflection this
using system.reflection; namespace stackoverflow35166571 { public class reflectioncalculator { public int calculate(string action, int a, int b) { var methodinfo = this.gettype().getmethod(action, bindingflags.instance | bindingflags.nonpublic); var result = (int)methodinfo.invoke(this, new object[] { a, b }); return result; } private int multiply(int a, int b) { return * b; } } }
a call like
var calc = new reflectioncalculator(); var result = calc.calculate("multiply", 10, 3); // 30
a call using inputs like
var calc = new reflectioncalculator(); array[position] = calc.calculate(action, array[position], value);
Comments
Post a Comment