C#GetMethod方法的应用实例讲解.docx

C#GetMethod方法的应用实例讲解

目录关于C#Type类GetMethod方法应用应用举例类设计类代码小结

关于C#Type类

Type表示类型声明:类类型、接口类型、数组类型、值类型、枚举类型、类型参数、泛型类型定义,以及开放或封闭构造的泛型类型。调用this.GetType()方法得到Type对象,可获取成员信息,如方法名、变量名。更多学习请参照以下链接:

本文以API模拟调用类应用实例介绍Type.GetMethod方法的实际应用。

GetMethod方法应用

GetMethod是获取当前Type的特定方法,具有多个重载,我们在这里介绍GetMethod(stringname,System.Reflection.BindingFlagsbindingAttr)即使用指定的绑定约束搜索指定方法。

其中stringname表示要搜索的方法名称,System.Reflection.BindingFlags枚举可见下表:

序号筛选器标志说明1BindingFlags.Instance或BindingFlags.Static必须指定实例或静态方可有效返回2BindingFlags.Public搜索当前Type中包含的公共方法3BindingFlags.NonPublic搜索当前Type中包含的非公共方法、私有方法、内部方法和保护方法4BindingFlags.FlattenHierarchy在层次结构中的包括public和protected静态成员;private继承类中的静态成员不包括在层次结构中5BindingFlags.IgnoreCase忽略方法name的大小写进行搜索6BindingFlags.DeclaredOnly如果只搜索Type声明的方法,则搜索只是继承的方法

应用举例

类设计

创建一个CCAPI类处理数据回应,该类设计如下:

序号成员类型说明1HttpContexthttpc=HttpContext.Current;属性System.Web.HttpContext,相当于被包装组合的网络请求,我们可以通过HttpContext访问诸如网络传递GET或POST提交的数据、文件等等2voidinit()方法处理请求,执行对应的接口功能并返回Json结果3stringRunGetTypeMethod(stringmethodName,object[]paras)方法GetMethod方法的应用,根据请求动作执行对应的方法

运行的基本流程如下图:

用户通过访问API地址,携带getType参数,参数值跟方法名称,后台init()方法通过HttpContext.Current进行请求处理,执行RunGetTypeMethod(methodA,null)方法,查找API列表库中对应的方法名称methodA,并执行stringmethodA()方法,该方法返回Json处理结果。

类代码

示例代码如下:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

usingSystem.Web;

usingSystem.Data;

usingSystem.Web.SessionState;

usingSystem.Collections;

usingSystem.Data.SqlClient;

usingSystem.IO;

usingSystem.Reflection;

namespaceCCAPI

publicclassCCAPI

publicHttpContexthttpc=HttpContext.Current;

publicCCAPI()

publicvoidinit()

stringgetType=httpc.Request[getType];

if(getType==null)

httpc.Response.Write({\errcode\:2,\errmsg\:\暂时不能提供服务,未提供合法getType值。\});

httpc.Response.End();

return;

stringresultJson=;

resultJson=RunGetTypeMe

文档评论(0)

1亿VIP精品文档

相关文档