C#工具类(包含获取枚举描述方法)

时间:2023-03-10 01:57:48
C#工具类(包含获取枚举描述方法)

//把一个对象转换成功键值对字典格式

var obj = new { CustomerId = customerId };

var dic = obj.ToDictionray();

public static class ObjectExtension
    {
        public static Dictionary<string, object> ToDictionary(this object obj)
        {
            if (obj == null) return new Dictionary<string, object>();

var element = obj as List<BsonElement>;
            if (element != null)
            {
                return element.ToDictionary(e => e.Name, e => (object)e.Value);
            }
            var doc = obj as QueryDocument;
            if (doc != null)
            {
                return doc.ToDictionary(e => e.Name, e => (object)e.Value);
            }

Dictionary<string, object> objects =
                obj.GetType()
                    .GetProperties()
                    .Where(propertyInfo => propertyInfo.CanRead)
                    .ToDictionary(propertyInfo => propertyInfo.Name,
                        propertyInfo =>
                        {
                            object value = propertyInfo.GetValue(obj,
                                new object[0]);

if (value != null && value.GetType().IsClass &&
                                value.GetType() != typeof (string))
                            {
                                return value.ToDictionary();
                            }
                            return value;
                        });

return objects;
        }
    }

//获取枚举描述方法

Util.GetEnumDescription((Enums.IntegralTypeDetail) 1);

public enum IntegralTypeDetail
    {
        购物积分 = 1,
        投诉补偿 = 2,
        推荐注册奖励 = 3

  }

public static class Util
    {
        private static string _letters = "0123456789";
        private static string _alphanums = "0123456789abcdefghijklmnopqrstuvwxyz";
       
        public static string GetEnumDescription<T>(T value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false
            );

if (attributes != null &&
                attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }

public static T ParseDescriptionToEnum<T>(string description)
        {
            Array array = Enum.GetValues(typeof(T));
            var list = new List<T>(array.Length);
            for (int i = 0; i < array.Length; i++)
            {
                list.Add((T)array.GetValue(i));
            }

var dict = list.Select(v => new
            {
                Value = v,
                Description = GetEnumDescription(v)
            }
                       )
                           .ToDictionary(x => x.Description, x => x.Value);
            return dict[description];
        }

public static void BindEnum<T>(DropDownList ddl,params int[] ignore) where T:struct
        {
            ddl.Items.Clear();
            ddl.Items.Add(new ListItem("请选择...",""));
            var arr = Enum.GetValues(typeof(T));
            foreach (dynamic v in arr)
            {
                if(ignore!=null&&ignore.Contains((int)v)) continue;
                ddl.Items.Add(new ListItem(GetEnumDescription(v),((int)v).ToString()));
            }
           
        }

public static string GenerateIntegralPwd()
        {
            return GenerateNumString(8);
        }

public static string GenerateNumString(int length)
        {
            return GenerateFrom(length, _letters,false);
        }

public static string GenerateString(int length,bool upper=false)
        {
            return GenerateFrom(length, _alphanums,upper);
        }

static string GenerateFrom(int length,string array,bool upper)
        {
            var sb = new StringBuilder();
            var m = array.Length;
            for (int i = 0; i < length; i++)
            {
                var idx = Guid.NewGuid().GetHashCode()%m;
                idx = Math.Abs(idx);
                sb.Append(array[idx]);
            }
            var ret = sb.ToString();
            if (upper) ret = ret.ToUpper();
            return ret;
        }

public static int ToInt(object obj,int def=0)
        {
            var str = obj == null ? string.Empty : obj.ToString();
            int t;
            if (int.TryParse(str, out t)) return t;
            else return def;
        }

public static decimal ToDecimal(object obj, decimal def = 0)
        {
            var str = obj == null ? string.Empty : obj.ToString();
            return ToDecimal(str);
        }

public static decimal ToDecimal(string str, decimal def = 0)
        {
            decimal t;
            if (decimal.TryParse(str, out t)) return t;
            else return def;
        }

public static bool ToBool(object obj)
        {
            return Convert.ToBoolean(obj);
        }

public static string HtmlAnchor(string onclick, string text, string href = "javascript:void(0)")
        {
            return string.Format("<a href=\"{0}\" onclick=\"{1}\">{2}</a>", href, onclick, text);
        }

public static string CreateLink(string url, Dictionary<string, string> parameters)
        {
            var query = string.Join("&", parameters.Select(d => d.Key + "=" + d.Value));
            return url.Contains("?") ? url + "&" + query : url + "?" + query;
        }

public static string GetMD5(string s, string encoding)
        {
            MD5 md5 = MD5.Create();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(encoding).GetBytes(s));
            var sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

public static string OneOf(params string[] list)
        {
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item)) return item;
            }
            return string.Empty;
        }

public static bool AnyEmpty(params string[] list)
        {
            return list.Any(string.IsNullOrWhiteSpace);
        }

public static bool OneOf(this int v,params int[] list)
        {
            return list.Any(x => x == v);
        }

#region DateTime Util

public static string ToStr(this DateTime? date, string format = "yyyy-MM-dd")
        {
            return date == null ? string.Empty : date.Value.ToString(format);
        }

public static string ToStr(this DateTime date, string format = "yyyy-MM-dd")
        {
            return date.ToString(format);
        }
        #endregion
    }