• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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
    }


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
从C,C++,JAVA和C#看String库的发展(一)----C语言和C++篇发布时间:2022-07-18
下一篇:
C#数据库连接池发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap