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


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

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

1  TolerantCast 匿名類型轉換

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

//創建匿名類型
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);
}
 

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

 

3 Capitalize 字符串首字母大寫

直接對字符串操作,將字符串的首字母改成大寫,源代碼參考如下:

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上有很多這個需求的代碼,參考下面的程序代碼:

 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 給數組中的每個元素賦值

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM