C# 擴展方法實際應用整理

由於在項目中經常要針對基本的類型進行處理,因此寫了如下的擴展類進行類的擴展。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;

/// <summary>
///StringExtender 的摘要說明
/// </summary>
public static class StringExtender
{
    #region Hashtable 擴展

    /// <summary>
    /// 嘗試將鍵和值添加到字典中:如果不存在,才添加;存在,不添加也不拋導常
    /// </summary>
    public static Hashtable TryAdd<TKey, TValue>(this Hashtable dict, TKey key, TValue value)
    {
        if (dict.ContainsKey(key) == false) dict.Add(key, value);
        return dict;
    }
    /// <summary>
    /// 將鍵和值添加或替換到字典中:如果不存在,則添加;存在,則替換
    /// </summary>
    public static Hashtable AddOrReplace<TKey, TValue>(this Hashtable dict, TKey key, TValue value)
    {
        dict[key] = value;
        return dict;
    }
    /// <summary>
    /// 獲取與指定的鍵相關聯的值,如果沒有則返回輸入的默認值
    /// </summary>
    public static TValue GetValue<TKey, TValue>(this Hashtable dict, TKey key, TValue defaultValue = default(TValue))
    {
        return dict.ContainsKey(key) ? (TValue)dict[key] : defaultValue;
    }
    /// <summary>
    /// 向字典中批量添加鍵值對
    /// </summary>
    /// <param name="replaceExisted">如果已存在,是否替換</param>
    public static Hashtable AddRange<TKey, TValue>(this Hashtable dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
    {
        foreach (var item in values)
        {
            if (dict.ContainsKey(item.Key) == false || replaceExisted)
                dict[item.Key] = item.Value;
        }
        return dict;
    }

    #endregion

    #region Dictionary<TKey, TValue>擴展

    /// <summary>
    /// 嘗試將鍵和值添加到字典中:如果不存在,才添加;存在,不添加也不拋導常
    /// </summary>
    public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        if (dict.ContainsKey(key) == false) dict.Add(key, value);
        return dict;
    }
    /// <summary>
    /// 將鍵和值添加或替換到字典中:如果不存在,則添加;存在,則替換
    /// </summary>
    public static Dictionary<TKey, TValue> AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        dict[key] = value;
        return dict;
    }
    /// <summary>
    /// 獲取與指定的鍵相關聯的值,如果沒有則返回輸入的默認值
    /// </summary>
    public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
    {
        return dict.ContainsKey(key) ? dict[key] : defaultValue;
    }
    /// <summary>
    /// 向字典中批量添加鍵值對
    /// </summary>
    /// <param name="replaceExisted">如果已存在,是否替換</param>
    public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
    {
        foreach (var item in values)
        {
            if (dict.ContainsKey(item.Key) == false || replaceExisted)
                dict[item.Key] = item.Value;
        }
        return dict;
    }

    #endregion

    /// <summary>
    /// 將給定的對象轉化爲string[] ,ArrayList,List<string>,object[]
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string[] ToArrayStr(this object obj)
    {
        string[] arrStr = null;
        if (IsNullOrEmpty(obj)) { return arrStr; }
        if (obj.GetType() == typeof(ArrayList))
        {
            ArrayList arr = obj as ArrayList;
            arrStr = arr.ToArray(typeof(string)) as string[];
        }
        else if (obj.GetType() == typeof(List<string>))
        {
            List<string> list = obj as List<string>;
            arrStr = list.ToArray();
        }
        else if (obj.GetType() == typeof(object[]))
        {
            object[] list = obj as object[];
            arrStr = (string[])ArrayList.Adapter((Array)list).ToArray(typeof(string));
        }
        return arrStr;
    }

    /// <summary>
    /// 給定的數組轉化爲ArrayList
    /// </summary>
    /// <param name="array"></param>
    /// <returns></returns>
    public static ArrayList ToArrayList(this string[] array)
    {
        if (array == null)
            return null;

        ArrayList list = new ArrayList();
        foreach (string str in array)
        {
            list.Add(str);
        }
        return list;
    }

    public static string _ToString(this string[] array, string Separated)
    {
        string Result = "";
        if (array == null)
        {
            return Result;
        }
        foreach (string a in array)
        {
            Result += a + Separated;
        }
        Result = Result.Substring(0, Result.Length - Separated.Length);
        return Result;
    }
    /// <summary>
    /// 轉換爲枚舉,忽略大小寫
    /// </summary>
    /// <param name="EnumVal"></param>
    /// <param name="EnumType"></param>
    /// <returns></returns>
    public static object ToEnum(this string EnumVal, Type EnumType, bool ignoreCase)
    {
        object oEnum = Enum.Parse(EnumType, EnumVal, ignoreCase);
        return oEnum;
    }
    /// <summary>
    /// 轉換爲枚舉,忽略大小寫
    /// </summary>
    /// <param name="EnumVal"></param>
    /// <param name="EnumType"></param>
    /// <returns></returns>
    public static object ToEnum(this string EnumVal, Type EnumType)
    {
        return ToEnum(EnumVal, EnumType, true);

    }

    public static int IndexOf(this string[] array, string Value)
    {
        int Result = -1;
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] == Value)
            {
                Result = i;
                break;
            }
        }
        return Result;
    }

    /// <summary>
    /// 將 ▓A▓▓NA▓ 轉化爲 'A','NA' 格式
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string GetSqlIn(this object obj)
    {
        return obj.ReplaceX(TBCSysConst.SPLIT_STR + TBCSysConst.SPLIT_STR, "','").ReplaceX(TBCSysConst.SPLIT_STR, "'");
    }

    /// <summary>
    /// ArrayList,string[],Array,string, 把以","分隔的字符串,轉變爲在SQL中可直接運行的字符串
    /// 111,www,rrrr   變成 '111','www','rrr'
    /// </summary>
    /// <param name="str"></param>
    /// <param name="Separated"></param>
    /// <returns></returns>
    public static string GetStringSqlFilter(this object str)
    {
        StringBuilder builder = new StringBuilder();
        if (str.GetType() == typeof(ArrayList))
        {
            ArrayList list = str as ArrayList;
            foreach (string temp in list)
            {
                builder.AppendFormat(",'{0}'", temp.Replace("'", string.Empty));
            }
        }
        else if (str.GetType() == typeof(string[]))
        {
            string[] list = str as string[];
            foreach (string temp in list)
            {
                builder.AppendFormat(",'{0}'", temp.Replace("'", string.Empty));
            }
        }
        else if (str.GetType() == typeof(Array))
        {
            Array list = str as Array;
            foreach (string temp in list)
            {
                builder.AppendFormat(",'{0}'", temp.Replace("'", string.Empty));
            }
        }
        else if (str.GetType() == typeof(string))
        {
            string[] arrStr = str.ToList(",");
            foreach (string temp in arrStr)
            {
                builder.AppendFormat(",'{0}'", temp.Replace("'", string.Empty));
            }
        }
        if (builder.Length > 0)
            return builder.ToStringX().Substring(1);
        else
            return string.Empty;
    }

    /// <summary>
    /// 去除空格
    /// </summary>
    /// <param name="str"></param>
    /// <param name="flag">是否去除內部的空格</param>
    /// <returns></returns>
    public static string Trim(this string str, bool flag)
    {
        if (!str.IsNullOrEmpty())
        {
            str = (flag) ? Regex.Replace(str, @"\s+", string.Empty) : str.Trim();
        }
        return str;
    }

    /// <summary>
    /// 將字符串轉化爲數字
    /// </summary>
    /// <param name="item">轉化失敗返回0</param>
    /// <returns></returns>
    public static int ToInt(this object item)
    {
        int IntResult = 0;
        if (!item.IsNullOrEmpty())
        {
            int.TryParse(item.ToStringX(), out IntResult);
        }
        return IntResult;
    }

    /// <summary>
    /// 將字符串轉化爲金額
    /// </summary>
    /// <param name="item">轉化失敗返回0</param>
    /// <returns></returns>
    public static double ToMoney(this object item)
    {
        double IntResult = 0.00;
        if (!item.IsNullOrEmpty())
        {
            double.TryParse(item.ToString(), out IntResult);
        }
        return IntResult;
    }

    /// <summary>
    /// 將字符串轉化爲金額
    /// </summary>
    /// <param name="item">轉化失敗返回0</param>
    /// <returns></returns>
    public static decimal ToMoney(this object item, int Num)
    {
        decimal DecResult = decimal.Zero;
        if (!item.IsNullOrEmpty())
        {
            decimal.TryParse(item.ToString(), out DecResult);

            DecResult = decimal.Round(DecResult, Num);
        }
        return DecResult;
    }

    /// <summary>
    /// 查看字符串是否匹配指定的正則表達式 如 "12345".IsMatch(@"\d+");
    /// </summary>
    /// <param name="s"></param>
    /// <param name="pattern"></param>
    /// <returns></returns>
    public static bool IsMatch(this string s, string pattern)
    {
        if (s == null) return false;
        else return Regex.IsMatch(s, pattern);
    }


    /// <summary>
    /// 將匹配的字符串過濾返回 如 "ljn615".Match("[a-zA-Z]+");
    /// </summary>
    /// <param name="s"></param>
    /// <param name="pattern"></param>
    /// <returns></returns>
    public static string Match(this string s, string pattern)
    {
        if (s == null) return string.Empty;
        return Regex.Match(s, pattern).Value;
    }


    /// <summary>
    /// 判斷字符是否爲空或者NULL,true則爲空,false不爲空
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool IsNullOrEmpty(this object value)
    {
        if (value != null && value != DBNull.Value)
        {
            Type objType = value.GetType();
            if (objType == typeof(DataSet))
            {
                DataSet ds = value as DataSet;
                //沒有表
                if (ds.Tables.Count == 0) return true;
                //只有一個表,但是表裏沒有數據
                if (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0) return true;
                if (ds.Tables.Count > 1)
                {
                    foreach (DataTable dt in ds.Tables)
                    {
                        //只要有大於0的就不爲空
                        if (dt.Rows.Count > 0)
                        {
                            return false;
                        }
                    }
                }
            }
            if (objType == typeof(DataTable))
            {
                DataTable dt = value as DataTable;
                if (dt.Rows.Count == 0) return true;
            }

            string val = value.ToString().Trim().ToUpper();
            if (val == "NULL" || val == "UNDEFINED" || val == "{}") return true;
            return (val.Length == 0);
        }
        return true;
    }


    /// <summary>
    /// 格式化字符串
    /// </summary>
    /// <param name="format">要格式化的字符串,如 "今天是:{0:yyyy年MM月dd日 星期ddd}".FormatWith(DateTime.Today);</param>
    /// <param name="args">可選的</param>
    /// <returns></returns>
    public static string FormatWith(this string format, params object[] args)
    {
        return string.Format(format, args);
    }

    /// <summary>
    /// 將對象內指定的字符串(不區分大小寫)替換爲新的字符串,如果爲null則返回空字符串
    /// </summary>
    /// <param name="item"></param>
    /// <param name="OldStr">被替換的字符串</param>
    /// <param name="NewStr">新的字符串</param>
    /// <returns></returns>
    public static string ReplaceX(this object item, string OldStr, string NewStr)
    {
        string StrResult = string.Empty;
        if (!item.IsNullOrEmpty())
        {
            StrResult = item.ToString().Trim().Replace(OldStr, NewStr).Replace(OldStr.ToLower(), NewStr).Replace(OldStr.ToUpper(), NewStr);
        }
        return StrResult;
    }

    /// <summary>
    /// 將對象轉化爲字符串後並截取字符
    /// </summary>
    /// <param name="item"></param>
    /// <param name="start">開始截取的索引</param>
    /// <returns></returns>
    public static string ToStringX(this object item, int start)
    {
        string StrResult = string.Empty;
        if (!item.IsNullOrEmpty())
        {
            StrResult = item.ToString().Trim();
            if (start < StrResult.Length)
            {
                StrResult = StrResult.Substring(start);
            }
        }
        return StrResult;
    }
    /// <summary>
    /// 將對象轉化爲字符串後並截取字符
    /// </summary>
    /// <param name="item"></param>
    /// <param name="start">開始截取的索引</param>
    /// <param name="length">要截取的長度</param>
    /// <returns></returns>
    public static string ToStringX(this object item, int start, int length)
    {
        string StrResult = string.Empty;
        if (!item.IsNullOrEmpty())
        {
            StrResult = item.ToString().Trim();
            if (length <= StrResult.Length - start)
            {
                StrResult = StrResult.Substring(start, length);
            }
        }
        return StrResult;
    }

    /// <summary>
    /// 將對象轉化爲字符串,如果爲null則返回空字符串
    /// </summary>
    /// <param name="item"></param>
    /// <param name="flag">可選的,是否去掉空格</param>
    /// <returns></returns>
    public static string ToStringX(this object item)
    {
        string StrResult = string.Empty;
        if (!item.IsNullOrEmpty())
        {
            if (item.GetType() == typeof(byte[]))
            {
                byte[] b = item as byte[];
                StrResult = Encoding.Default.GetString(b);
            }
            else
            {
                StrResult = item.ToString().Trim();
            }
        }
        return StrResult;
    }

    /// <summary>
    /// 將對象轉化爲字符串,如果爲null則返回空字符串
    /// </summary>
    /// <param name="item"></param>
    /// <param name="flag">可選的,是否轉換成大寫,否則false小寫</param>
    /// <returns></returns>
    public static string ToStringX(this object item, bool flag)
    {
        string StrResult = string.Empty;
        if (!item.IsNullOrEmpty())
        {
            if (flag)
                StrResult = item.ToString().Trim().ToUpper();
            else
                StrResult = item.ToString().Trim().ToLower();
        }
        return StrResult;
    }

    /// <summary>
    /// 將字符串以指定的分隔符轉換成數組
    /// </summary>
    /// <param name="item"></param>
    /// <param name="Separated">分隔符</param>
    /// <returns></returns>
    public static string[] ToList(this object item, char Separated)
    {
        return ToList(item, Separated.ToString());
    }
    /// <summary>
    /// 將字符串以指定的分隔符轉換成數組
    /// </summary>
    /// <param name="item"></param>
    /// <param name="Separated">分隔符</param>
    /// <returns></returns>
    public static string[] ToList(this object item, string Separated)
    {
        string StrResult = item.ToStringX();
        string[] arrResult = null;
        if (!Separated.IsNullOrEmpty() && StrResult.Contains(Separated))
        {
            StrResult = StrResult.Replace(Separated, TBCSysConst.REPLACE_SPLIT_CHAR.ToString());
            arrResult = StrResult.Split(TBCSysConst.REPLACE_SPLIT_CHAR);
        }
        else
        {
            arrResult = new string[] { StrResult };
        }
        return arrResult;
    }

    /// <summary>
    /// 轉全角(SBC case)
    /// </summary>
    /// <param name="input">任意字符串</param>
    /// <returns>全角字符串</returns>
    public static string ToSBC(this string input)
    {
        char[] c = input.ToCharArray();
        for (int i = 0; i < c.Length; i++)
        {
            if (c[i] == 32)
            {
                c[i] = (char)12288;
                continue;
            }
            if (c[i] < 127)
            {
                c[i] = (char)(c[i] + 65248);
            }
        }
        return new string(c);
    }

    /// <summary>
    /// 轉半角(DBC case)
    /// </summary>
    /// <param name="input">任意字符串</param>
    /// <returns>半角字符串</returns>
    public static string ToDBC(this string input)
    {
        char[] c = input.ToCharArray();
        for (int i = 0; i < c.Length; i++)
        {
            if (c[i] == 12288)
            {
                c[i] = (char)32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
            {
                c[i] = (char)(c[i] - 65248);
            }
        }
        return new string(c);
    }

    /// <summary>
    /// 將對象轉化爲字符串,如果爲null則返回空字符串
    /// </summary>
    /// <param name="item"></param>
    /// <param name="flag">可選的,是否去掉空格</param>
    /// <returns></returns>
    public static string ToStringX(this object item, FormatEnum format)
    {
        string StrResult = string.Empty;
        if (!item.IsNullOrEmpty())
        {
            if (!format.IsNullOrEmpty())
            {
                try
                {
                    switch (format)
                    {
                        case FormatEnum.SmallDate:
                            DateTime SmallDate = Convert.ToDateTime(item);
                            StrResult = SmallDate.ToString("yyyy-MM-dd");
                            break;
                        case FormatEnum.FullDate:
                            DateTime FullDate = Convert.ToDateTime(item);
                            StrResult = FullDate.ToString("yyyy-MM-dd HH:mm:ss");
                            break;
                        case FormatEnum.FileReName:
                            DateTime FileReName = Convert.ToDateTime(item);
                            StrResult = FileReName.ToString("yyyyMMddHHmmss");
                            break;
                        case FormatEnum.SmallYear:
                            DateTime SmallYear = Convert.ToDateTime(item);
                            StrResult = SmallYear.ToString("yyyyMMdd");
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception)
                {
                    StrResult = item.ToString().Trim();
                }
            }
            else
                StrResult = item.ToString().Trim();
        }
        return StrResult;
    }
}
/// <summary>
/// 格式化的枚舉
/// </summary>
public enum FormatEnum
{
    /// <summary>
    /// yyyy-MM-dd
    /// </summary>
    SmallDate = 0,
    /// <summary>
    /// yyyyMMdd
    /// </summary>
    SmallYear,
    /// <summary>
    /// yyyy-MM-dd HH:mm:ss
    /// </summary>
    FullDate,
    /// <summary>
    /// yyyyMMddHHmmss
    /// </summary>
    FileReName
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章