
首先声明一点,大家都会说反射的效率低下,但是大多数的框架能少了反射吗?当反射能为我们带来代码上的方便就可以用,如有不当之处还望大家指出
1,项目结构图如下所示:一个ClassLb类库项目,一个为测试用的testReflect的webform项目,testReflect添加对ClassLb类库项目的引用
2,ClassLb类库项目中我添加了两个非常简单的类,代码如下
public class Class1
{
public static string Insert(string a, string b)
{
return a + "," + b + "插入成功在Class1中";
}
public static string Update(string a, string b)
{
return a + "," + b + "更新成功在Class1中";
}
} public class Class2
{
public static string Insert(string a, string b)
{
return "a,b插入成功在Class2中";
}
public static string Update(string a, string b)
{
return "a,b更新成功在Class2中";
}
}
3,webform项目在Default.aspx.cs中的测试代码如下:注意,添加命名空间using System.Reflection;
/// <summary>
/// 获取类型
/// </summary>
/// <param name="assemblyName">程序集名</param>
/// <param name="typeName">类名</param>
/// <returns></returns>
private Type AccessType(string assemblyName, string typeName)
{ Type type = null; Assembly assembly = Assembly.Load(assemblyName); if (assembly == null) throw new Exception("Could not find assembly!"); type = assembly.GetType(assemblyName + "." + typeName); if (type == null) throw new Exception("Could not find type!"); return type; }
/// <summary>
/// 执行方法获取结果
/// </summary>
/// <param name="assemblyName">程序集名</param>
/// <param name="typeName">类名</param>
/// <param name="method">方法名</param>
/// <param name="arguments">方法所需参数</param>
/// <returns></returns>
public object ExecuteMethod(string assemblyName, string typeName, string method, params object[] arguments)
{ object returnObject = null; Type type = AccessType(assemblyName, typeName); returnObject = type.InvokeMember(method, BindingFlags.Default | BindingFlags.InvokeMethod, null, null, arguments); return returnObject; }
4,测试代码如下:
protected void Page_Load(object sender, EventArgs e)
{ string a = ExecuteMethod("ClassLb", "Class1", "Insert", "sxd", "").ToString();
Response.Write(a + "</br>");
string b = ExecuteMethod("ClassLb", "Class1", "Update", "sxd", "").ToString();
Response.Write(b + "</br>");
string c = ExecuteMethod("ClassLb", "Class2", "Insert", "sxd", "").ToString();
Response.Write(c + "</br>");
string d = ExecuteMethod("ClassLb", "Class2", "Update", "sxd", "").ToString();
Response.Write(d + "</br>");
}
5,执行结果:
6,心得体会,我做的上一个项目用到的是Jquery通过ajax调用webservice,webservice调用类库方法,每一个对象基本都有增删改查操作,我在webservice中就要建四个操作的方法供ajax调用,写了很多的webservice,每个webservice又有好几个方法,浪费了很多的时间,当我用上面所示的反射的时候只需用一个webservice,一个方法,前台ajax调用的时候给我传入相应的参数即可,这样会大大提高开发速度,这只是我的一点体会,如果大家有更好的方法请一起跟大家分享