Extension methods must be defined in non-generic static classes.

Source: Internet
Author: User

Http://blog.sina.com.cn/s/blog_a5193ed401016mvb.html

 

An extension method is a special static method, but it can be called like an instance method of an extension type.

Extension methods are defined as static methods, but they are called through the instance method syntax. Their first parameter specifies the type of the method to act on, and the parameter usesThisThe modifier is the prefix.

The extension method requirements are as follows:

1. The first parameter is the type to be extended or to be operated. This is called "extended type"

2. to specify the extension method, add the this modifier before the extended type name.

3. Access the method as an extension method. Use the using command to import the extension type namespace, or make the extension type and calling code in the same namespace.

    1. // The extension method must be defined in a non-generic static class.
    2. Public static class qzwtest
    3. {
    4. // Extension Method
    5. Public static string [] qzw (this string Str)
    6. {
    7. Return Str. Split (New char [] {'', ','});
    8. }
    9. }
    10. Class Program
    11. {
    12. Static int main ()
    13. {
    14. String teststr = "Qian zhuowen is Miao, Xian Jing ";
    15. // Call the Extension Method
    16. String [] testarray = teststr. qzw ();
    17. Foreach (string s in testarray)
    18. {
    19. Console. writeline (s );
    20. }
    21. Console. readkey ();
    22. Return 0;
    23. }
    24. }

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.