Introduction to C # extension methods

Source: Internet
Author: User

As the name implies, this is an operation that can extend the C # class, as the MSDN statement says:

The extension method enables you to add a method to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. ”

is usually used to extend the classes that we can't modify, such as
String,int,datarow,datatable these.

For example, a string type has a method called Contains, which can be used to test whether a specified string or character is contained in the strings.

Now I need to determine if there are no strings in the string I've drawn up. What to do, I wrote a Nocontains method, if the string does not contain an array of strings in the argument, it returns to true, and then as an extension method loaded into the string type.

The code is as follows:

This allows you to use the Nocontains method of the string directly.

Examples of use are as follows:

Array is a string array, and you can extend the method of the string class as long as you define such a static class in your project.

With regard to the definition of extension methods, the idea on MSDN is:

Extension methods are defined as static methods, but they are called through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier.

Specifically, the extension method must be placed in a static class, the extension method itself must be a static method, and then the first parameter of the extension method must be the type you want to extend, and precede the This modifier.

PS: It is not easy to express in concise words, read more books to improve the ability to express.

Blog Original address: http://blog.deali.cn/?p=832

My public number: Dealiaxy

Introduction to C # extension methods

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.