I'm trying to solve some simple study task, which includes writing an interpreter of some simple language with 4 methods - Set, Sum, Print, Remove; first 2 methods have 2 arguments - variable name and int value to set to variable or sum to its current value, and last 2 methods have only one argument - variable name
The method that I'm writing takes string , for example "set a 3" or "print a", and should work as interpreter of this string (do appropriate actions).
The obvious way is to use switch
construction (switch by first word), but I've read that it's always better to use Dictionary
instead of switch
, so I've defined
Dictionary<string, Action<ActionArg>> methods
, where ActionArg
is defined supertype with 2 inherited types:
abstract class ActionArg {}
class ActionArgVal : ActionArg { public string Val {get; set; } }
class ActionArgValVar : ActionArgVal { public int Var {get; set; } }
, and have defined 4 methods, for example,
void Set(ActionArgValVar) { ... }
But when I'm trying to write methods = new Dictionary<string, Action<ActionArg>> { {"set", Set}, ... }
, there occurs an error, because Action<ActionArgValVar>
couldn't be assigned to Action<ActionArg>
because of contravariance of Action
.
Is there any way to solve this using Dictionary
or tasks like this are better to be solved by simple switch
construction?