GetMethod in Interface as field of class c#? -


this program calculator. examine have:

public interface ifunction{     string name {get; }     double eval(); } 

and

public class subtract:ifunction{     private double x,y;     public double eval(){      return x - y;      }     public string name{         { return "subtract";}     } }  public class add:ifunction{     private double x, y;     public double eval(){      return x + y;      }     public string name{         { return "add";}     } } 

i have write class, has string field operation. name of string field must use name{ get; } ifunction, can "add" or "subtract". if "subtract", implement subtract operation, calling eval() method subtract class, , etc; how make polymorphic calling of method in class calculator? must calculator class implement interface?

 public class calculator{     private double leftoperand, rightoperand;     private string operation;     public double calculate(){     /*here must call eval() subtract or add, depending    on `operation` */     } } 

you can have calculator contain list of ifunction:

private ilist<ifunction> functions; 

then iterate list when calculate called:

ifunction function = functions.firstordefault(f => f.name == operation); 

then if null throw exception or give default value back.

also mentioned @rob in comments ifunctions need way assign x , y values can property:

public double x { get; set; } 

or modifying interface eval method accepts them arguments:

double eval(double x, double y); 

so putting following in calculate

ifunction function = functions.firstordefault(f => f.name == operation); if (function == null) {     //or return default value     throw new argumentoutofrangeexception("operation", "unable find operation in list of available ones"); }  return eval(leftoperand, rightoperand); 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -