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
No comments:
Post a Comment