分享.NET系統開發過程當中積累的擴展方法

.NET 3.5提供的擴展方法特性,能夠在不修改原類型代碼的狀況下擴展它的功能。下面分享的這些擴展方法大部分來自於Code Project或是Stackoverflow,.NET爲此還有一個專門提供擴展方法的網站(extensionMethod)。css

涵蓋類型轉換,字符串處理,時間轉化,集合操做等多個方面的擴展。html

1  TolerantCast 匿名類型轉換

這個需求來源於界面中使用BackgroundWorker,爲了給DoWork傳遞多個參數,又不想定義一個類型來完成,因而我會用到TolerantCast方法。參考以下的代碼:api

//建立匿名類型
var parm = new { Bucket = bucket, AuxiliaryAccIsCheck = chbAuxiliaryAcc.Checked, AllAccountIsCheck = chbAllAccount.Checked };
backgroundWorker.RunWorkerAsync(parm);


 private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
//解析轉換匿名類型
  var parm = e.Argument.TolerantCast(new { Bucket = new RelationPredicateBucket(), AuxiliaryAccIsCheck = false, AllAccountIsCheck = false });

 

2  ForEach 集合操做

這個方法的定義很簡單但也很實用,它的使用方法以下:數組

var buttons = GetListOfButtons() as IEnumerable<Button>; 
buttons.ForEach(b => b.Click());

擴展方法的源代碼定義只有一行,源代碼以下:網站

public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)
{
    foreach (var item in @enum) mapFunction(item);
}
 

當我想對一個集合中的每一個元素執行相同的操做時,經常會藉助於此方法實現。this

 

3 Capitalize 字符串首字母大寫

直接對字符串操做,將字符串的首字母改爲大寫,源代碼參考以下:spa

public static string Capitalize(this string word)
{
      if (word.Length <= 1)
          return word;

      return word[0].ToString().ToUpper() + word.Substring(1);
}

4  ToDataTable 強類型對象集合轉化爲DataTable

開發中常常會遇到將List<Entity>轉化爲DataTable,或是反之將DataTable轉化爲List<Entity>,stackoverflow上有不少這個需求的代碼,參考下面的程序代碼:code

 public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();

            // column names  
            PropertyInfo[] oProps = null;

            if (varlist == null) return dtReturn;

            foreach (T rec in varlist)
            {
                // Use reflection to get property names, to create table, Only first time, others will follow  
                if (oProps == null)
                {
                    oProps = ((Type) rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;

                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof (Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }

                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }

                DataRow dr = dtReturn.NewRow();

                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                                                                                      (rec, null);
                }

                dtReturn.Rows.Add(dr);
            }
            return dtReturn;
        }

 

5  SetAllValues 給數組中的每一個元素賦值

實現給數組中的每一個元素賦相同的值。htm

public static T[] SetAllValues<T>(this T[] array, T value)
{
     for (int i = 0; i < array.Length; i++)
     {
           array[i] = value;
     }

     return array;
}

6 ToXml 序列化對象爲Xml格式

能夠將一個對象序列化爲Xml格式的字符串,保存對象的狀態。對象

public static string ToXml<T>(this T o) where T : new()
{
        string retVal;
        using (var ms = new MemoryStream())
        {
              var xs = new XmlSerializer(typeof (T));
               xs.Serialize(ms, o);
               ms.Flush();
               ms.Position = 0;
               var sr = new StreamReader(ms);
               retVal = sr.ReadToEnd();
        }
        return retVal;
}

 

7  Between 值範圍比較

能夠判斷一個值是否落在區間範圍值中。

public static bool Between<T>(this T me, T lower, T upper) where T : IComparable<T>
{
      return me.CompareTo(lower) >= 0 && me.CompareTo(upper) < 0;
}

相似這樣的操做,下面的方法是取2個值的最大值。

public static T Max<T>(T value1, T value2) where T : IComparable
{
     return value1.CompareTo(value2) > 0 ? value1 : value2;
}
 

8  StartDate DueDate 開始值或末值

業務系統中經常會用到時間比較,若是系統是用DateTime.Now變量與DateTime.Today來做比較,前者老是大於後者的,爲此須要作一個簡單轉化,根據須要將值轉化爲開始值或末值,也就是0點0分0秒,或是23時59分59秒。

public static DateTime ConverToStartDate(this DateTime dateTime)
{
     return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
}

public static DateTime ConverToDueDate(this DateTime dateTime)
{
      return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59);
}
 
 

9 First Day Last Day 月的第一天或是最後一天

public static DateTime First(this DateTime current)
{
       DateTime first = current.AddDays(1 - current.Day);
       return first;
}

public static DateTime Last(this DateTime current)
{
      int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);

       DateTime last = current.First().AddDays(daysInMonth - 1);
       return last;
}


 

10 Percent 百分比值

計算前一個數值佔後一個數值的百分比,經常使用於統計方面。

public static decimal PercentOf(this double position, int total)
{
     decimal result = 0;
     if (position > 0 && total > 0)
         result=(decimal)((decimal)position / (decimal)total * 100);
     return result;
}

擴展方法源代碼下載:http://files.cnblogs.com/files/JamesLi2015/ExtensionMethod.zip

相關文章
相關標籤/搜索