Home   Cover Cover Cover Cover
 

Scripting environment

/csbook/solutions/18/A15.cs
using System;
using System.Reflection;

public class InvalidCallException: Exception {}

// sample methods to be called
public class Methods {
  
  public static void GCD(int x, int y) {
    int x0 = x, y0 = y;
    int rest = x % y;
    while (rest != 0) { x = y; y = rest; rest = x %y; }
    Console.WriteLine("GCD({0},{1}) = {2}", x0, y0, y);
  }
  
  public static void Power(int x, int y) {
    int res = 1;
    for (int i = 0; i < y; i++) res *= x;
    Console.WriteLine("Power({0},{1}) = {2}", x, y, res);
  }
  
}

// calls a public static void method with an arbitrary number
// of int parameters
public class Script {
  
  public static void Call(string cmd) {
    try {
      //--- split the command into its parts
      int pos = cmd.IndexOf('.');
      if (pos < 0) throw new InvalidCallException();
      string className = cmd.Substring(0, pos);
      cmd = cmd.Substring(pos+1);
      pos = cmd.IndexOf('(');
      if (pos < 0) throw new InvalidCallException();
      string methodName = cmd.Substring(0, pos);
      cmd = cmd.Substring(pos+1);
      if (cmd.Length == 0 || cmd[cmd.Length-1] != ')') throw new InvalidCallException();
      cmd = cmd.Substring(0, cmd.Length-1);
      string[] parStrings = cmd.Split(',');

      //--- call the method
      Type t = Type.GetType(className);
      MethodInfo m = t.GetMethod(methodName);
      object[] par = new object[parStrings.Length];
      for (int i = 0; i < parStrings.Length; i++) {
        par[i] = Convert.ToInt32(parStrings[i]);
      }
      m.Invoke(null, par);
    } catch (InvalidCallException) {
      Console.WriteLine("-- synopsis: Class.Method(int,int,...)");
    } catch {
      Console.WriteLine("-- failed");
    }
  }
  
  static void Main(string[] arg) {
    for (;;) {
      Console.Write(">");
      string cmd = Console.ReadLine();
      if (cmd == "") return;
      Call(cmd);
    }
  }
}