常用扩展方法总结

来源:互联网 发布:理光复印机刷卡软件 编辑:程序博客网 时间:2024/05/16 09:35

1,字符串转数字。

public static int ToInt(this string s, int defValue){      try      {          return Convert.ToInt32(str);      }      catch (Exception)      {          return defValue;      }}

适合位置:System
2,空字符串检测。

        public static bool NullOrEmpty(this string s)        {            return string.IsNullOrEmpty(s);        }

适合位置:System
3,把一组数字转换为逗号分隔的字符串。

        public static string ToStringDot(this IEnumerable<int> s)        {            if (s == null || s.Count() < 1)            {                return string.Empty;            }            System.Text.StringBuilder Stsb = new System.Text.StringBuilder();            foreach (int a in s)            {                Stsb.Append(a);                Stsb.Append(',');            }            return Stsb.ToString().Substring(0, Stsb.Length - 1);        }

适合位置:System.Collections.Generic
4,把逗号分隔的数字串转换为数字数组(3的逆运算)。

        public static List<int> ToListIntByDot(this string s, bool Allow0 = false, bool Distinct = false)        {            List<int> Li = new List<int>();            if (s.NullOrEmpty())                return Li;            foreach (string a in s.Split(','))            {                int i = a.ToInt(-1);                if (Allow0)                {                    if (i > -1)                        Li.Add(i);                }                else                {                    if (i > 0)                        Li.Add(i);                }            }            if (Distinct)                Li = Li.Distinct().ToList();            return Li;        }

适合位置:System.Collections.Generic
5,不出错地获取实体的某个属性。

        public static TKey Field<T, TKey>(this T t, Expression<Func<T, TKey>> keySelector) where T:class        {            if (t == null)                return default(TKey);            else                return keySelector.Compile().Invoke(t);        }

适合位置:System

这5个扩展方法基本在我做过的各个项目里都有身影。1和2应用非常广泛,3和4用在Sql语句拼接、URL里的Id传递时的拼接等地方。5的使用比较有特点,在前台页面里经常写这样的从数据库获取某个实例的语句:BLL.Member.GetModel((int)Eval(“memberid”)).Username这样的句子获取不到实体的时候会出错,所以需要先判断一下实体是否为空,代码就变成了:BLL.Member.GetModel((int)Eval(“memberid”))==null?string.Empty:BLL.Member.GetModel((int)Eval(“memberid”)).Username 这样就不会出错了,但是他会读取两次数据库。即使使用了缓存,这样写也不够优雅,这个时候用第5个就很方便了。直接这样写代码:BLL.Member.GetModel((int)Eval(“memberid”)).Field(x=>x.Username) 就行了,实体为空时直接返回 default(string) 也就是 null 不会报错。

0 0
原创粉丝点击