此为C# 3.0新加入的特性
作用是可以动态的向某个类添加静态函数
举例1:
namespace ExtensionMethods { public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } }
这就是向String类中添加了一个静态函数叫WordCount
使用的时候
string s = "Hello Extension Methods"; int i = s.WordCount();
举例2:
namespace HS.Common { /// <summary> /// 扩展函数 /// </summary> public static class ExtensionFunction { /// <summary> /// 获取枚举描述信息 /// </summary> /// <param name="enumSubitem"></param> /// <returns></returns> public static string GetDesc(this Enum enumSubitem) { string strValue = enumSubitem.ToString(); FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue); Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return strValue; } else { DescriptionAttribute da = (DescriptionAttribute)objs[0]; return da.Description; } } /// <summary> /// 通用分页函数 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list">待分页集合</param> /// <param name="page">页码</param> /// <param name="pagesize">页大小</param> /// <param name="totalPage">总页数</param> /// <returns></returns> public static IEnumerable<T> Pager<T>(this IEnumerable<T> list, int page, int pagesize, out int totalPage) { int total = list.Count();//总记录数 totalPage = total / pagesize == 0 ? total / pagesize : total / pagesize + 1;//总页数 if (page < 1) page = 1; else if (page > totalPage) page = totalPage; if (page <= totalPage) list = list.Skip((page - 1) * pagesize).Take(pagesize); else list = list.Skip((page - 1) * pagesize); return list; } /// <summary> /// Time32转 DateTime /// </summary> /// <param name="timestamp">时间戳</param> /// <returns></returns> public static DateTime ToDateTime(this int timestamp) { //时间戳转换 double secs = Convert.ToDouble(timestamp); DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(secs); return dt; } /// <summary> /// DateTime转 Time32 /// </summary> /// <param name="dt">时间</param> /// <returns></returns> public static int ToTime32t(this DateTime dt) { DateTime defaultTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified); dt = dt.AddHours(8); return (int)((dt.Ticks - defaultTime.Ticks) / 1000 / 10000); } /// <summary> /// 从数据行中取值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dr"></param> /// <param name="key">列名</param> /// <param name="defaultValue">默认值</param> /// <returns></returns> public static T Get<T>(this System.Data.DataRow dr, string key, T defaultValue = default(T)) where T : IConvertible { if (!dr.Table.Columns.Contains(key)) return defaultValue; return HS.Common.CConvert.Get<T>(dr[key], defaultValue); } } }
调用时: string Roles = dr.Get<string>("Roles");