1. 程式人生 > 其它 >獲取實體類裡面所有的名稱、DESCRIPTION值

獲取實體類裡面所有的名稱、DESCRIPTION值

        //獲取實體類裡面所有的名稱、DESCRIPTION值
        public Dictionary<string, string> GetDescription<T>(T t)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            PropertyInfo[] ps = t.GetType().GetProperties();
            foreach (var item in
ps) { if (item.CustomAttributes.Where(p => p.AttributeType.Name.Contains("DescriptionAttribute")).FirstOrDefault() != null) { var des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description; dic.Add(item.Name, des); } }
return dic; } //獲取實體類裡面所有的名稱、值、DESCRIPTION值 public string GetProperties<T>(T t) { string tStr = string.Empty; if (t == null) { return tStr; } PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (properties.Length <= 0) { return tStr; } foreach (PropertyInfo item in properties) { string name = item.Name; //名稱 object value = item.GetValue(t, null); // string des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 屬性值 if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { tStr += string.Format("{0}:{1}:{2},", name, value, des); } else { GetProperties(value); } } return tStr; }