How to use reflection to call a method and pass parameters whose types are unknown at compile time?

Posted by MandoMando on Stack Overflow See other posts from Stack Overflow or by MandoMando
Published on 2010-05-13T20:39:01Z Indexed on 2010/05/13 21:24 UTC
Read the original article Hit count: 321

Filed under:
|
|

I'd like to call methods of a class dynamically with parameter values that are "parsed" from a string input.

For example: I'd like to call the following program with these commands:

c:>myprog.exe MethodA System.Int32 777
c:>myprog.exe MethodA System.float 23.17
c:>myprog.exe MethodB System.Int32& 777
c:>myprog.exe MethodC System.Int32 777 System.String ThisCanBeDone

static void Main(string[] args)
{
     ClassA aa = new ClassA();
     System.Type[] types = new Type[args.Length / 2];
     object[] ParamArray = new object[types.Length];

     for (int i=0; i < types.Length; i++)
       {
          types[i] = System.Type.GetType(args[i*2 + 1]);
      // LINE_X: this will obviously  cause runtime error invalid type/casting
          ParamArray[i] = args[i*2 + 2];  

     MethodInfo callInfo = aa.GetType().GetMethod(args[0],types);
     callInfo.Invoke(aa, ParamArray);
}

// In a non-changeable classlib:

public class ClassA { public void MethodA(int i) { Console.Write(i.ToString()); }

    public void MethodA(float f) { Console.Write(f.ToString()); }

    public void MethodB(ref int i) { Console.Write(i.ToString()); i++; }

    public void MethodC(int i, string s) { Console.Write(s + i.ToString()); }

    public void MethodA(object o) { Console.Write("Argg! Type Trapped!"); }
}

"LINE_X" in the above code is the sticky part. For one, I have no idea how to assign value to a int or a ref int parameter even after I create it using Activator.CreatInstance or something else. The typeConverter does come to mind, but then that requires an explicit compile type casting as well.

Am I looking at CLR with JavaScript glasses or there is way to do this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET