转载自:https://www.cnblogs.com/coderJiebao/p/CSharp09.html
在 C# 代码中,有些时候只知道方法的名字(string),需要调用该方法,那么就需要用到 C# 的反射机制。下面是一个简单的 demo。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
namespace Map
{
class Test
{
public void Method()
{
Console.WriteLine("Method无参数调用");
}
public void Method(string str)
{
Console.WriteLine("有一个参数调用成功,参数是"+ str);
}
public string Method(string str1, string str2)
{
Console.WriteLine("有两个参数调用成功,参数是:" + str1+"第二个参数是:"+ str2);
string className = this.GetType().FullName;
return className;
}
}
class Program
{
static void Main(string[] args)
{
string strClass = "Map.Test";//命名空间+类名
string sreMethod = "Method";//方法名
Type type;//存储类
object obj;//存储类的实例
type = Type.GetType(strClass);//通过类名获取同名类
obj = System.Activator.CreateInstance(type);//创建实例
MethodInfo method = type.GetMethod (sreMethod, new Type[]{});//获取方法信息
object[] parameters = null;
method.Invoke(obj, parameters);//调用方法,参数为空
method = type.GetMethod(sreMethod, new Type[] { typeof(string) });//获取方法信息
parameters = new object[] { "你好" };
method.Invoke(obj, parameters);//调用方法有参数
method = type.GetMethod(sreMethod, new Type[] { typeof(string), typeof(string) });
parameters = new object[] { "你好", "大熊" };
string result = (string)method.Invoke(obj, parameters);
Console.WriteLine("Method的返回值" + result);
string ClassName = MethodBase.GetCurrentMethod().ReflectedType.FullName;
Console.WriteLine("当前静态方法类名" + ClassName);
Console.ReadKey();
}
}
}
需要注意的是,类名是命名空间+类名,不然会找不到类
另外补充:方法必须是public否则找不到,为null。