您的位置:首页 > 编程语言 > C#

C#扩展方法集合类

2015-10-26 17:17 537 查看
扩展方法是C#常用简化代码的手段,原本含义为在系统类的基础上增加自己的方法,比如"xxx{0}xx".format()这种用法,使得软件开发更为简便。在此贴个扩展方法类,用于技术交流

using System;
using System.Text;
using System.Security.Cryptography;
using System.Web.Script.Serialization;

namespace SqlHelper {
public static class ExtensionMethods {
/// <summary>
/// 返回元素在数组中的索引
/// </summary>
/// <param name="a">数组</param>
/// <param name="o">元素</param>
/// <returns>索引</returns>
public static int inArray (this object[] a, object o) {
for (int i = 0; i < a.Length; i++) {
if (a[i] == o) return i;
}
return -1;
}

/// <summary>
/// 返回元素在数组中的索引
/// </summary>
/// <param name="o">元素</param>
/// <param name="a">数组</param>
/// <returns>索引</returns>
public static int inArray (this object o, object[] a) {
return a.inArray (o);
}

/// <summary>
/// URL转码
/// </summary>
/// <param name="s">原始URL</param>
/// <returns>新URL</returns>
public static string encodeUrl (this string s) {
if (s.isNullOrEmpty ()) return "";
return s.Replace (":", "%3a").Replace ("/", "%2f").Replace (" ", "+").Replace ("\\", "%2c").Replace ("=", "%3d").Replace ("?", "%3f").Replace ("%", "%25").Replace ("&", "%26");
}

/// <summary>
/// 简化string.Format函数的调用
/// </summary>
/// <param name="s">格式化字符串</param>
/// <param name="args">参数列表</param>
/// <returns>格式化后的字符串</returns>
public static string format (this string s, params object[] args) {
return string.Format (s, args);
}

/// <summary>
/// 简化Convert.ToInt32函数的调用
/// </summary>
/// <param name="o">需要转为数字的对象</param>
/// <returns>数字</returns>
public static Int32 toInt32(this object o) {
try {
return Convert.ToInt32(o);
} catch (Exception ex) {
throw ex;
}
}

/// <summary>
/// 简化Convert.ToInt64函数的调用
/// </summary>
/// <param name="o">需要转为数字的对象</param>
/// <returns>数字</returns>
public static Int64 toInt64 (this object o) {
try {
return Convert.ToInt64 (o);
} catch (Exception ex) {
throw ex;
}
}

/// <summary>
/// 简化Convert.ToDouble函数的调用
/// </summary>
/// <param name="o">需要转为数字的对象</param>
/// <returns>数字</returns>
public static double toDouble (this object o) {
try {
return Convert.ToDouble (o);
} catch (Exception ex) {
throw ex;
}
}

/// <summary>
/// MD5加密
/// </summary>
/// <param name="s">需要加密的数据</param>
/// <param name="loop">加密次数</param>
/// <returns>加密后的数据</returns>
public static string md5Encrypt (this string s, int loop = 3) {
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider ();
for (; loop > 0; loop--) {
s = BitConverter.ToString (md5.ComputeHash (UTF8Encoding.Default.GetBytes (s))).Replace ("-", "");
}
return "{0}-{1}-{2}-{3}-{4}".format (s.Substring (0, 8), s.Substring (8, 4), s.Substring (12, 4), s.Substring (16, 4), s.Substring (20, 12));
}

/// <summary>
/// 简化string.Join函数调用
/// </summary>
/// <param name="s">数组对象</param>
/// <param name="separator">分隔符</param>
/// <returns>字符串</returns>
public static string join (this string[] s, string separator = ";") {
if (s == null) return "";
return string.Join (separator, s);
}

/// <summary>
/// 二维数组垂直string.Join函数调用
/// </summary>
/// <param name="ss">数组对象</param>
/// <param name="col">垂直第几列</param>
/// <param name="separator">分隔符</param>
/// <returns>字符串</returns>
public static string join (this string[][] ss, int col, string separator = ";") {
if (ss == null || ss.Length == 0)
return "";
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < ss.Length; i++) {
sb.Append (ss[i][col]).Append (separator);
}
return sb.Remove (sb.Length - separator.Length, separator.Length).toString ();
}

/// <summary>
/// 简化string.IsNullOrEmpty函数调用
/// </summary>
/// <param name="s">字符串</param>
/// <returns>是否为空</returns>
public static bool isNullOrEmpty (this string s) {
return string.IsNullOrEmpty (s);
}

/// <summary>
/// 字符串或其他类型转为日期时间对象
/// </summary>
/// <param name="o">需要转换的对象</param>
/// <returns>日期时间类型</returns>
public static DateTime toDateTime(this object o) {
try {
return Convert.ToDateTime(o);
} catch (Exception ex) {
throw ex;
}
}

/// <summary>
/// 格式化小数
/// </summary>
/// <param name="o">需要格式化小数的对象</param>
/// <param name="afterPoint">保留小数点后几位</param>
/// <returns>字符串型数据</returns>
public static string formatDecimal(this object o, int afterPoint = 2) {
try {
return string.Format(string.Format("{{0:F{0}}}", afterPoint), o);
} catch (Exception ex) {
throw ex;
}
}

/// <summary>
/// 格式化日期
/// </summary>
/// <param name="o">需要格式化的日期</param>
/// <param name="sDate">日期分隔符</param>
/// <returns>字符串</returns>
public static string formatDate(this DateTime o, char sDate = '-') {
if (o == null) return "";
return o.ToString(string.Format("yyyy{0}MM{0}dd", sDate));
}

/// <summary>
/// 格式化日期(汉字)
/// </summary>
/// <param name="o">需要格式化的日期</param>
/// <returns>字符串</returns>
public static string formatDateLong(this DateTime o) {
if (o == null) return "";
return o.ToString("yyyy年MM月dd日");
}

/// <summary>
/// 格式化时间
/// </summary>
/// <param name="o">需要被格式化的时间</param>
/// <param name="sTime">分隔符,默认冒号</param>
/// <returns>格式化后的时间</returns>
public static string formatTime (this DateTime o, char sTime = ':') {
if (o == null) return "";
return o.ToString (string.Format ("HH{0}mm{0}ss", sTime));
}

/// <summary>
/// 格式化时间(汉字)
/// </summary>
/// <param name="o">需要被格式化的时间</param>
/// <returns>格式化后的时间</returns>
public static string formatTimeLong (this DateTime o) {
if (o == null) return "";
return o.ToString ("HH时mm分ss秒");
}

/// <summary>
/// 格式化日期时间
/// </summary>
/// <param name="o">需要格式化的日期时间</param>
/// <param name="sDate">日期分隔符</param>
/// <param name="sTime">时间分隔符</param>
/// <returns>字符串</returns>
public static string formatDateTime(this DateTime o, char sDate = '-', char sTime = ':') {
if (o == null) return "";
return string.Format ("{0} {1}", o.formatDate (sDate), o.formatTime (sTime));
}

/// <summary>
/// 格式化日期时间(汉字)
/// </summary>
/// <param name="o">需要格式化的日期时间</param>
/// <returns>字符串</returns>
public static string formatDateTimeLong(this DateTime o) {
if (o == null) return "";
return string.Format ("{0} {1}", o.formatDateLong (), o.formatTimeLong ());
}

/// <summary>
/// 将布尔值转为字符串
/// </summary>
/// <param name="b">布尔值</param>
/// <returns>字符串</returns>
public static string boolToString (this bool b) {
try {
return b ? "ok" : "fealure";
} catch (Exception ex) {
return ex.Message;
}
}

/// <summary>
/// 将一个对象序列化为json字符串
/// </summary>
/// <param name="o">可序列化对象</param>
/// <returns>json字符串</returns>
public static string toJson (this object o) {
try {
if (o == null) return "[]";
return new JavaScriptSerializer ().Serialize (o);
} catch (Exception ex) {
return ex.Message;
}
}

/// <summary>
/// 将json字符串反序列化为一个对象
/// </summary>
/// <typeparam name="T">返回值类型</typeparam>
/// <param name="s">json字符串</param>
/// <returns>反序列化后的对象</returns>
public static T fromJson<T> (this string s) {
try {
if (s.isNullOrEmpty ()) return default (T);
return new JavaScriptSerializer ().Deserialize<T> (s);
} catch (Exception ex) {
throw ex;
}
}

/// <summary>
/// 用于可能为空的对象转字符串,避免对象为空引发的错误
/// </summary>
/// <param name="o">object对象</param>
/// <returns>字符串</returns>
public static string toString (this object o) {
if (o == null) return "";
return o.ToString ();
}

/// <summary>
/// 向上取整
/// </summary>
/// <param name="n">浮点数</param>
/// <returns>计算结果</returns>
public static int cell (this double d) {
int i = (int) d;
if (d > i)
return i + 1;
return i;
}

/// <summary>
/// 向下取整
/// </summary>
/// <param name="n">浮点数</param>
/// <returns>计算结果</returns>
public static int floor (this double d) {
return (int) d;
}

//供ID检查用
private static Func<char, bool> isSign = c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');

/// <summary>
/// 检查是否为标准32位ID格式
/// </summary>
/// <param name="s">ID</param>
/// <returns>是否标准</returns>
public static bool isId32 (this string s) {
if (s.isNullOrEmpty () || s.Length != 32) return false;
for (int i = 0; i < s.Length; i++) {
if (!isSign (s[i])) return false;
}
return true;
}

/// <summary>
/// 检查是否为标准36位ID格式
/// </summary>
/// <param name="s">ID</param>
/// <returns>是否标准</returns>
public static bool isId36 (this string s) {
if (s.isNullOrEmpty () || s.Length != 36) return false;
for (int i = 0; i < s.Length; i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
if (s[i] != '-') return false;
} else {
if (!isSign (s[i])) return false ;
}
}
return true;
}
}
}
源代码中建个类ExtensionMethods,并在其中加入扩展方法,就能使用了。上面的代码用法如下:
string[] ss;//字符串数组,其他类型也行
string s;//字符串

//返回某个对象在对象数组中的索引
int index = s.inArray(ss);//返回字符串在字符串数组中的索引
int index2 = ss.inArray(s);//效果同上

//字符串转码
string encoded = "http://www.xxx.com".encodeUrl();//转码,生成的效果类似于:http%3a%2f%2fwww.xxx.com

//字符串格式化
string formated = "aaaa{0}cccc".format("111");//生成的效果为:aaaa111cccc

//格式转换
int intval = "45".toInt32();//值为45
Int64 int64val = "4234892374872344".toInt64();//值为4234892374872344
double dbval = "3.14159".toDouble();//值为3.14159
DateTime dt = "2008-08-08".toDateTime();//将字符串转为日期时间对象

//加密
string password = "admin888".md5Encrypt();//值为如下格式:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,其中X为16进制数

//字符串拼接
s = ss.join();//假如ss为{"a", "b"},那么s值为:a;b,默认为分号分割

bool b = s.isNullOrEmpty();//如果s等于null或者s的长度为0,则返回true

string decimalstr = dbval.formatDecimal();//将浮点数据转为字符串,默认保留2位小数,可自定义保留多少位小数

//看上面的代码估计大家都会使用了,其他调用代码省略……

上面是用法简单介绍。关于toJson与fromJson两个序列化有关操作,需要注意的是json键与C#类的公有属性必须一一对应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 扩展 ExtensionMethods