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.