using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace WaterCloud.Code { public class ReflectionHelper { private static ConcurrentDictionary dictCache = new ConcurrentDictionary(); #region 得到类里面的属性集合 /// /// 得到类里面的属性集合 /// /// /// /// public static PropertyInfo[] GetProperties(Type type, string[] columns = null) { PropertyInfo[] properties = null; if (dictCache.ContainsKey(type.FullName)) { properties = dictCache[type.FullName] as PropertyInfo[]; } else { properties = type.GetProperties(); dictCache.TryAdd(type.FullName, properties); } if (columns != null && columns.Length > 0) { // 按columns顺序返回属性 var columnPropertyList = new List(); foreach (var column in columns) { var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault(); if (columnProperty != null) { columnPropertyList.Add(columnProperty); } } return columnPropertyList.ToArray(); } else { return properties; } } public static object GetObjectPropertyValue(T t, string propertyname) { Type type = typeof(T); PropertyInfo property = type.GetProperty(propertyname); if (property == null) return string.Empty; object o = property.GetValue(t, null); if (o == null) return string.Empty; return o; } #endregion /// /// 反射获取模块名 /// /// public static string GetModuleName(int count=2) { try { string className = new StackFrame(count, true).GetMethod().DeclaringType.FullName; className = className.Split('+')[0]; className = className.Split('.').LastOrDefault(); string moduleName = className.Substring(0, className.Length - 7); return moduleName; } catch (Exception ex) { LogHelper.WriteWithTime(ex); return ""; } } /// /// 反射获取方法名 /// /// public static string GetClassName(int count = 4) { try { if (GlobalContext.SystemConfig.Debug == true && count == 4) { count++; } string className = new StackFrame(count, true).GetMethod().DeclaringType.FullName; className = className.Split('+')[0]; className = className.Split('.').LastOrDefault(); return className; } catch (Exception ex) { LogHelper.WriteWithTime(ex); return ""; } } } }