反射的妙用-类名方法名做参数进行方法调用实例demo

王朝学院·作者佚名  2016-05-21
窄屏简体版  字體: 小  |  中  |  大  |  超大  

反射的妙用-类名方法名做参数进行方法调用实例demo首先声明一点,大家都会说反射的效率低下,但是大多数的框架能少了反射吗?当反射能为我们带来代码上的方便就可以用,如有不当之处还望大家指出

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", "123").ToString(); Response.Write(a + "</br>"); string b = ExecuteMethod("ClassLb", "Class1", "Update", "sxd", "123").ToString(); Response.Write(b + "</br>"); string c = ExecuteMethod("ClassLb", "Class2", "Insert", "sxd", "123").ToString(); Response.Write(c + "</br>"); string d = ExecuteMethod("ClassLb", "Class2", "Update", "sxd", "123").ToString(); Response.Write(d + "</br>"); }

5,执行结果:

6,心得体会,我做的上一个项目用到的是Jquery通过Ajax调用webservice,webservice调用类库方法,每一个对象基本都有增删改查操作,我在webservice中就要建四个操作的方法供ajax调用,写了很多的webservice,每个webservice又有好几个方法,浪费了很多的时间,当我用上面所示的反射的时候只需用一个webservice,一个方法,前台ajax调用的时候给我传入相应的参数即可,这样会大大提高开发速度,这只是我的一点体会,如果大家有更好的方法请一起跟大家分享

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航