c# - Choose my method name for delegate without reflection -


my delegate...

private delegate double calculatedelegate(double x, double y); 

code declareing delegate...

private calculatedelegate calculate;  

my methods use in delegates...

private double add(double x, double y) { return x + y; } private double subtract(double x, double y) { return x - y; } 

how execute desired method...

calculate = new calculatedelegate(add); 

or...

calculate = new calculatedelegate(subtract); 

this works actual code contains many more 'functions' avoid using switch/if statement. need write new method send in.

the calc method (i usied action here thinking might work, not)

   public double calc(action methodname, double x, double y)     {         calculate = new calculatedelegate(methodname);  return calculate(x,y);      } 

how execute desired method.

 public void go() {    calc(add, 5,4); } 

is possible without reflection?

what solution, use dictionary of delegates keys equal names of delegates, @ example.:

public delegate double calculatedelegate(double x, double y);  public class test {             public calculatedelegate calculate;                 }  public class delegatecontainer {     public double add(double x, double y)     {         return x + y;     }     public double subtract(double x, double y)     {         return x - y;     }      public dictionary<string, calculatedelegate> collection = new dictionary<string, calculatedelegate>();     public delegatecontainer()     {         collection["add"] = add;         collection["subtract"] = subtract;     }      public calculatedelegate this[string name]     {                             {                             return collection[name];         }                 } }  public static void main() {             var target = new test();     var container = new delegatecontainer();     target.calculate = container["add"];     console.writeline("1 + 2 = " + target.calculate(1, 2));      target.calculate = container["subtract"];     console.writeline("5 - 2 = " + target.calculate(5, 2)); } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -