C # basics-Application of extension methods,

Source: Internet
Author: User

C # basics-Application of extension methods,

Recently I was interested in the extension method. I looked at the information and recorded several methods of the extension method.

I. basic use of the extension method:

Note: 1. Extension methods must be in static classes. 2 extension methods must declare static methods. 3 extension methods cannot call other custom methods.

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;        }

Ii. Extension Method generics: The above are all types of extension methods written to death, extension methods support generics as well:

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;        }

Iii. Delegation of generic methods: the generic method supports delegation, which facilitates data operations. The foreach method of the set is simulated below.

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

 

      

    

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.