using Nelibur.ObjectMapper; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Dynamic; using System.Linq; using System.Threading; namespace Hncore.Infrastructure.Extension { public static class ObjectExtension { /// /// 将对象[主要是匿名对象]转换为dynamic /// public static dynamic ToDynamic(this object obj, decimal defaultVal) { decimal result; if (obj != null) if (decimal.TryParse(obj.ToString(), out result)) return result; else return defaultVal; return defaultVal; } // This extension method is broken out so you can use a similar pattern with // other MetaData elements in the future. This is your base method for each. public static T GetAttribute(this object value) where T : Attribute { var type = value.GetType(); var memberInfo = type.GetMember(value.ToString()); if (!memberInfo.Any()) { return null; } var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false); return (T) attributes[0]; } // This method creates a specific call to the above method, requesting the // Description MetaData attribute. public static string GetDescription(this object value) { var desAttribute = value.GetAttribute(); if (desAttribute != null) { return desAttribute.Description; } var displayAttribute = value.GetAttribute(); if (displayAttribute != null) { return displayAttribute.Name ?? displayAttribute.Description; } return ""; } #region 得到枚举字典(key对应枚举的值,value对应枚举的注释) /// /// 得到枚举字典(key对应枚举的值,value对应枚举的注释) /// /// /// public static Dictionary ToDescriptionDictionary() { Array values = Enum.GetValues(typeof(TEnum)); Dictionary nums = new Dictionary(); foreach (Enum value in values) { nums.Add(value, GetDescription(value)); } return nums; } #endregion #region 实体中string属性执行Trim() /// /// 对象string属性执行Trim() /// /// /// /// public static T ObjectStrTrim(this T t) where T:new () { if (t != null) { foreach (var pi in t.GetType().GetProperties()) { if (pi.PropertyType.Equals(typeof(string)) && pi.GetValue(t, null) != null)//判断属性的类型是不是String { pi.SetValue(t, pi.GetValue(t, null).ToString().Trim(), null);//给泛型的属性赋值 } } } return t; } #endregion #region public static T save(this T obj,string key) where T:class,new() { Dictionary dic = c.Value ?? new Dictionary(); dic.Add(key,obj); c.Value = dic; return obj; } public static AsyncLocal> c=new AsyncLocal>(); #endregion #region 对象转换 public static T MapTo(this Object model) { var productDto = TinyMapper.Map(model); return productDto; } public static IEnumerable MapsTo(this Object model) { var generic = model.GetType().GetGenericTypeDefinition(); if (generic == typeof(List<>)) { return TinyMapper.Map>(model); } if (generic == typeof(Collection<>)) { return TinyMapper.Map>(model); } throw new Exception("不合法的转换"); } #endregion } }