C#工具:反射帮助类 泛型反射帮助类
程序员文章站
2022-07-11 09:52:26
反射帮助类 using System; using System.Reflection; using System.Data; using System.Drawing; using System.Resources; using System.ComponentModel; using Syste ......
反射帮助类
using system; using system.reflection; using system.data; using system.drawing; using system.resources; using system.componentmodel; using system.text; using system.io; namespace core.common { /// <summary> /// 反射辅助类 /// </summary> public static class reflecthelper { #region 成员读写 /// <summary> /// 通过数据行填充实体类型 /// </summary> /// <param name="model">实体对象</param> /// <param name="drow">数据行</param> public static void fillinstancevalue(object model, datarow drow) { type type = model.gettype(); for (int i = 0; i < drow.table.columns.count; i++) { propertyinfo property = type.getproperty(drow.table.columns[i].columnname); if (property != null) { property.setvalue(model, drow[i], null); } } } /// <summary> /// 通过数据只读器填充实体类型 /// </summary> /// <param name="model">实体对象</param> /// <param name="dr">数据只读器</param> public static void fillinstancevalue(object model, idatareader dr) { type type = model.gettype(); for (int i = 0; i < dr.fieldcount; i++) { propertyinfo property = type.getproperty(dr.getname(i)); if (property != null) { property.setvalue(model, dr[i], null); } } } /// <summary> /// 获取实体相关属性的值 /// </summary> /// <param name="obj"></param> /// <param name="propertyname"></param> /// <returns></returns> public static object getinstancevalue(object obj, string propertyname) { object objret = null; if (!string.isnullorempty(propertyname)) { propertydescriptor descriptor = typedescriptor.getproperties(obj).find(propertyname, true); if (descriptor != null) { objret = descriptor.getvalue(obj); } } return objret; } #endregion #region 方法调用 /// <summary> /// 直接调用内部对象的方法/函数或获取属性(支持重载调用) /// </summary> /// <param name="reftype">目标数据类型</param> /// <param name="funname">函数名称,区分大小写。</param> /// <param name="objinitial">如果调用属性,则为相关对象的初始化数据,否则为null。</param> /// <param name="funparams">函数参数信息</param> /// <returns>运行结果</returns> public static object invokemethodorgetproperty(type reftype, string funname, object[] objinitial, params object[] funparams) { memberinfo[] mis = reftype.getmember(funname); if (mis.length < 1) { throw new invalidprogramexception(string.concat("函数/方法 [", funname, "] 在指定类型(", reftype.tostring(), ")中不存在!")); } else { methodinfo targetmethod = null; stringbuilder pb = new stringbuilder(); foreach (memberinfo mi in mis) { if (mi.membertype != membertypes.method) { if (mi.membertype == membertypes.property) { #region 调用属性方法get targetmethod = ((propertyinfo)mi).getgetmethod(); break; #endregion } else { throw new invalidprogramexception(string.concat("[", funname, "] 不是有效的函数/属性方法!")); } } else { #region 检查函数参数和数据类型 绑定正确的函数到目标调用 bool validparamslen = false, validparamstype = false; methodinfo curmethod = (methodinfo)mi; parameterinfo[] pis = curmethod.getparameters(); if (pis.length == funparams.length) { validparamslen = true; pb = new stringbuilder(); bool paramflag = true; int paramidx = 0; #region 检查数据类型 设置validparamstype是否有效 foreach (parameterinfo pi in pis) { pb.appendformat("parameter {0}: type={1}, name={2}\n", paramidx, pi.parametertype, pi.name); //不对null和接受object类型的参数检查 if (funparams[paramidx] != null && pi.parametertype != typeof(object) && (pi.parametertype != funparams[paramidx].gettype())) { #region 检查类型是否兼容 try { funparams[paramidx] = convert.changetype(funparams[paramidx], pi.parametertype); } catch (exception) { paramflag = false; } #endregion //break; } ++paramidx; } #endregion if (paramflag == true) { validparamstype = true; } else { continue; } if (validparamslen && validparamstype) { targetmethod = curmethod; break; } } #endregion } } if (targetmethod != null) { object objreturn = null; #region 兼顾效率和兼容重载函数调用 try { object objinstance = system.activator.createinstance(reftype, objinitial); objreturn = targetmethod.invoke(objinstance, bindingflags.invokemethod, type.defaultbinder, funparams, system.globalization.cultureinfo.invariantculture); } catch (exception) { objreturn = reftype.invokemember(funname, bindingflags.invokemethod, type.defaultbinder, null, funparams); } #endregion return objreturn; } else { throw new invalidprogramexception(string.concat("函数/方法 [", reftype.tostring(), ".", funname, "(args ...) ] 参数长度和数据类型不正确!\n 引用参数信息参考:\n", pb.tostring())); } } } /// <summary> /// 调用相关实体类型的函数方法 /// </summary> /// <param name="reftype">实体类型</param> /// <param name="funname">函数名称</param> /// <param name="funparams">函数参数列表</param> /// <returns>调用该函数之后的结果</returns> public static object invokefunction(type reftype, string funname, params object[] funparams) { return invokemethodorgetproperty(reftype, funname, null, funparams); } #endregion #region 资源获取 /// <summary> /// 获取程序集资源的位图资源 /// </summary> /// <param name="assemblytype">程序集中的某一对象类型</param> /// <param name="resourceholder">资源的根名称。例如,名为“myresource.en-us.resources”的资源文件的根名称为“myresource”。</param> /// <param name="imagename">资源项名称</param> public static bitmap loadbitmap(type assemblytype, string resourceholder, string imagename) { assembly thisassembly = assembly.getassembly(assemblytype); resourcemanager rm = new resourcemanager(resourceholder, thisassembly); return (bitmap)rm.getobject(imagename); } /// <summary> /// 获取程序集资源的文本资源 /// </summary> /// <param name="assemblytype">程序集中的某一对象类型</param> /// <param name="resname">资源项名称</param> /// <param name="resourceholder">资源的根名称。例如,名为“myresource.en-us.resources”的资源文件的根名称为“myresource”。</param> public static string getstringres(type assemblytype, string resname, string resourceholder) { assembly thisassembly = assembly.getassembly(assemblytype); resourcemanager rm = new resourcemanager(resourceholder, thisassembly); return rm.getstring(resname); } /// <summary> /// 获取程序集嵌入资源的文本形式 /// </summary> /// <param name="assemblytype">程序集中的某一对象类型</param> /// <param name="charset">字符集编码</param> /// <param name="resname">嵌入资源相对路径</param> /// <returns>如没找到该资源则返回空字符</returns> public static string getmanifeststring(type assemblytype, string charset, string resname) { assembly asm = assembly.getassembly(assemblytype); stream st = asm.getmanifestresourcestream(string.concat(assemblytype.namespace, ".", resname.replace("/", "."))); if (st == null) { return ""; } int ilen = (int)st.length; byte[] bytes = new byte[ilen]; st.read(bytes, 0, ilen); return (bytes != null) ? encoding.getencoding(charset).getstring(bytes) : ""; } #endregion } }
泛型反射帮助类
using system; using system.collections.generic; using system.data; using system.data.sqlclient; using system.linq; using system.reflection; using system.text; using system.threading.tasks; namespace dal { public class expdal { /// <summary> /// 显示 /// </summary> /// <typeparam name="t"></typeparam> /// <returns></returns> public static list<t> getts<t>()where t:new() { //获取type对象,反射操作基本都是用type进行的 type type = typeof(t); string sql = "select * from expense"; sqldatareader dr = dbhelper.getdatareader(sql); //获取type对象的所有公共属性 propertyinfo[] info = type.getproperties(); list<t> modellist = new list<t>(); //定义泛型对象 t obj = default(t); while (dr.read()) { obj = new t(); foreach (propertyinfo item in info) { item.setvalue(obj, dr[item.name]); } modellist.add(obj); } dr.close(); return modellist; } /// <summary> /// 添加 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="nodel"></param> /// <returns></returns> public static int addexpense<t>(t nodel)where t : new() { type type = typeof(t); string sql = string.format("insert into {0} ", type.name); string val = ""; string link = "'"; //获取type对象所有公共属性 propertyinfo[] info = type.getproperties(); foreach (propertyinfo item in info) { val += link + item.getvalue(nodel) + link+",";//定义字段变量 } val = val.substring(0, val.length - 1); val += ")"; sql += "values(" + val.remove(0,4); //调用执行方法 return dbhelper.executenonquery(sql); } /// <summary> /// 修改 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="nodel"></param> /// <param name="id"></param> /// <returns></returns> public static int updateexpense<t>(t nodel,int id)where t:new() { type type = typeof(t); string sql = string.format("update {0} set ", type.name); propertyinfo[] info = type.getproperties(); string link = ""; foreach (propertyinfo item in info) { object val = item.getvalue(nodel); if (val!=null) { sql += link + item.name + "='" + val + "' "; link = ", "; } } sql = sql.remove(18, 12); sql += string.format(" where eid=" + id); return dbhelper.executenonquery(sql); } /// <summary> /// 删除 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="id"></param> /// <returns></returns> public static int deletebyeid<t>(int id)where t : new() { type type = typeof(t); string sql = string.format($"delete from {type.name} where eid={id}"); return dbhelper.executenonquery(sql); } } }
上一篇: 刚刚做b超又差点被保安拦住不让进了
下一篇: 学习笔记