Introduction and use of. net3.0. net3.5 Extension Method

Source: Internet
Author: User

Today, I saw someone asking me how to use this, and I feel I need to record it here. by the way, let's take a look at its usage and details. Note: A reference error will occur when using it in section 2.0. because this is the product after 3.0

Functions of the extension method:

You can directly extend the. netframe class library to reduceCodeQuantity.

Notes:
1. The class name of the class is invalid when the extension method is used.
2. The extension method must be a static method in the static class. The format of the static method has special requirements.
3. The extension method can also be used as a common static method.

When we see that the method with the "Small Arrow" is the extension method, enter the following code and then take a closer look at the icons of the method and extension method.

 

 

Using System;
Using System. Collections. Generic;
Using System. text;
Using System. Threading;

Namespace CSHARP. Test
{
Public   Class Program
{
Public   Static   Void Main ( String [] ARGs)
{
// Code call
Student =   New Student {name =   " Bbb " , Age =   20 };
Console. writeline (student. isvalue ( " Bbb " ));
// Output True
Console. writeline (student. truename ( " Bbb " ));
// Output True
Console. Readline ();
}

}< br> Public class Student
{< br> Public string name { Get ; set ;}

Public IntAge {Get;Set;}
}

Public   Static   Class Test
{
Public   Static   Bool Isvalue ( This Student student, Object O)
{
If (Student. Name = O)
{
Return   True ;
}
Return   False ;
}
}

Public   Static   Class Eoopoo
{
Public   Static   String Truename ( This Student student, Object O)
{
If (Student. Name = O)
{
Return Student. Name =   " Aaa " ;
}
Else
{
Return Student. Name;
}
}
}


}

In fact, according to the above meaning, the simplest sentence is that the class method can be extended to other classes by using the parameter this for 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.