反射幫助類 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); } } }泛型反射幫助類