您的位置:首页 > 其它

利用反射调用类中的方法

2015-07-08 14:11 281 查看
控制台程序

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

namespace MethodDemo
{
class Program
{
static void Main(string[] args)
{    //方法一
//Type type = typeof(MYclass);
//MethodInfo methodinfo = type.GetMethod("myfun");
//object obj = Activator.CreateInstance(type);
//methodinfo.Invoke(obj, new object[] { "name", "id" });
//方法二
Type type = typeof(MYclass);
//获取这个类的方法根据名称
MethodInfo methodinfo = type.GetMethod("myfun2");
//  实例化这个类
object obj = Activator.CreateInstance(type);
//或者这个方法所有的参数
ParameterInfo[] parms = methodinfo.GetParameters();
//定义调用方法要给的参数
object [] ps=new  object[parms.Length];
foreach(ParameterInfo item in parms)
{
//判断这个方法是不是类
if(item.GetType().IsClass)
{
//获取这个参数的所以属性
PropertyInfo[] prs = item.ParameterType.GetProperties();
//获取这个属性的类型
Type ptype = item.ParameterType;
//实例化这个参数对象
object itemobj = Activator.CreateInstance(ptype);
//循环这个类的所以属性,并给属性赋值
foreach(PropertyInfo itemprop in prs)
{
itemprop.SetValue(itemobj, itemprop.Name.ToString());//itemprop.Name.ToString() 可以是任何需要赋的值
}
ps[0]=itemobj;
}

}
methodinfo.Invoke(obj,ps);
Console.ReadKey();
}
}

public class MYclass
{
public void myfun(string name, string id)
{
Console.WriteLine(name);
Console.WriteLine(id);

}
public void myfun2(Userinfo userinfo)
{
Console.WriteLine(userinfo.Name);
Console.WriteLine(userinfo.ID);

}
}
public class Userinfo
{
public string Name { get; set; }

public string ID { get; set; }
}
}


  

可以加载所以的程序集来找类可以加载你想要加载判断的类

//加载所有的类
ICollection assemblies = BuildManager.GetReferencedAssemblies();
foreach (Assembly assembly in assemblies)
{
// 过滤以【System】开头的程序集,加快速度
if (assembly.FullName.StartsWith("System", StringComparison.OrdinalIgnoreCase))
continue;
foreach (Type t in assembly.GetExportedTypes())
{

if (t.IsClass == false)
continue;
if (t.Name.EndsWith("Controller"))
{
TypeInfo info = new TypeInfo();
info.Types = t;
info.Actions = new List<Action>();
List<Action> actions = new List<Action>();
foreach (MethodInfo p in t.GetMethods())
{
Action actinfo = new Action();
actinfo.MethodName = p.Name;
object[] obj = p.GetCustomAttributes(typeof(ActionAttribute), true);
foreach (ActionAttribute act in obj)
{
actinfo.ActionFalg = act.Value;
}
actinfo.Parameters = p.GetParameters();
info.Actions.Add(actinfo);
}

TypeInfolist.Add(info);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: