Monday, October 11, 2010

Invoke a Method when method name is in string format or stored in variable

Below is the code that will do the trick, wrapped in the method InvokeStringMethod. As you see, it takes only two lines to call another method given its name as a string, and its class name also as a string. Read the comments in the code to see how it works.

public static string InvokeStringMethod(string typeName, string methodName)
{
// Get the Type for the class
Type calledType = Type.GetType(typeName);

// Invoke the method itself. The string returned by the method winds up in s
String s = (String)calledType.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public |
BindingFlags.Static,
null,
null,
null);

// Return the string that was returned by the called method.
return s;
}

This method assumes that the called method has no parameters and returns a string. Pass the name of the method in parameter methodName, and the name of its class in typeName.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MyNameSpace
{

public class MyClass
{
public int returnvalue(int x)
{
return x;
}
}


class Program
{

static void Main(string[] args)
{
string s ="returnvalue";
Type t = typeof(MyClass);
ConstructorInfo CI = t.GetConstructor(new Type[] {});
object o = CI.Invoke(new object[]{});
MethodInfo MI = t.GetMethod(s);
object[] fnargs = new object[] {4};
Console.WriteLine("Function Returned values: " +MI.Invoke(o, fnargs).ToString());

}
}
}



references:http://www.codeproject.com/KB/cs/CallMethodNameInString.aspx

http://stackoverflow.com/questions/3906650/how-can-i-call-methods-from-a-regex-string/3906839#3906839

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates