C#基礎---擴充方法的應用

來源:互聯網
上載者:User

標籤:

    最近對擴充方法比較感興趣,就看了看資料,記錄一下擴充方法的幾種方法.

   一. 擴充方法的基本使用:  

    Note: 1. 擴充方法必須在靜態類中, 2 擴充方法必須聲明靜態方法,3 擴充方法裡面不能調用其他自訂方法。

public static int TryToInt(this string intStr)        {            int number = 0;            int.TryParse(intStr, out number);            return number;        }public static IEnumerable<string> StartsWith(this IEnumerable<string> ie, string startStr)        {            IEnumerable<string> returnIe = null;            if (ie != null)            {                returnIe = ie.Where(x => x.StartsWith(startStr));            }            return returnIe;        }

   二. 擴充方法之泛型: 上面都是對擴充方法的類型寫死了,擴充方法一樣支援泛型:

public static bool IsBetween<T>(this T value, T low, T high) where T : IComparable<T>        {            return value.CompareTo(low) >= 0 && value.CompareTo(high) < 0;        }

  三. 泛型方法之委託: 泛型方法可以支援委託,跟方便我們對資料的操作,下面來類比集合的foreach方法.

public static void Each<T>(this IEnumerable<T> items, Action<T> action)   {         foreach (T item in items)         {              action(item);         }    }

 

      

    

C#基礎---擴充方法的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.