问一个C#中函数方法调用的问题
请问各位高手,能否有什么方法使得我在只知道类中某些方法的名字时,动态的调用这些方法?
例如: Class A中有 一个名字叫 TestFunc()的方法,我只知道“TestFunc”这个字符串的话,如何去调用这个方法?
------解决方案--------------------比如有一个类库,包括两个函数,一个带参数,一个不带
using System;
using System.Reflection;
using System.Globalization;
namespace Lib
{
public class TestLib
{
private string _returnString;
public string ReturnString
{
get { return _returnString; }
set { _returnString = value; }
}
public TestLib()
{
Console.WriteLine( "Create a new instance ");
}
public TestLib(string str)
{
_returnString = str;
}
public void FunctionA(string [] paras)
{
try
{
string b=null;
for (int i=0;i <paras.Length;i++)
b+=paras[i];
Console.WriteLine( "A-- "+System.DateTime.Now.ToString( "yyyy-MM-dd hh:mm:ss:ffff ")+ "--- "+b);
}
catch (Exception ex)
{
Console.WriteLine( "FunctionA: "+ex.ToString());
}
}
public void FunctionB()
{
Console.WriteLine( "B-- "+System.DateTime.Now.ToString( "yyyy-MM-dd hh:mm:ss:ffff "));
}
}
}
------解决方案--------------------在程序中引用这个类,然后用反射调用
using System;
using System.Reflection;
using System.Globalization;
using Lib;
namespace Reflection
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
string[] a = new string[3];
a[0] = "ABCDE ";
a[1] = "DEFGHI ";
a[2] = "3454564675 ";
Call( "FunctionA ", a);
Call( "FunctionB ", null);
Console.ReadLine();
}
static void Call(string function_name, string [] paras)
{
string b = "Lib.dll ";
Assembly a = Assembly.LoadFrom(b);
Type t = a.GetType( "Lib.TestLib ");//( "TestLib ");
try
{
//Console.WriteLine(t.FullName);
if (paras != null)
{
MethodInfo m = t.GetMethod(function_name, new Type[] { typeof(string[]) });
Object obj = Activator.CreateInstance(t);
Console.WriteLine( "------------ " + obj.GetType());
m.Invoke(obj, new object[] { paras });
}
else
{
MethodInfo m = t.GetMethod(function_name);
Object obj = Activator.CreateInstance(t);
Console.WriteLine( "------------ " + obj.GetType());
m.Invoke(obj, null);
}
}
catch (Exception ex)
{
Console.WriteLine( "Main: "+ex.ToString());
}
}
}
}
------解决方案--------------------namespace Test
{
class Program
{
static void Main(string[] args)
{