Although I have used the extension method before, I have never carefully summarized what is the extension method. I was asked in the interview the day before yesterday what is the extension method and when to use it. I did not answer the question, now I have found it on the Internet and made a summary. I hope that my friends who have read this article will correct me.
It is often referenced in other DLL projects. Assume that there is a student class in the DLL, which only contains the getname () method. If you need the getage () method, you cannot modify the DLL source code, what should I do? There are two ways to do this: Inherit the student class and extend the methods in student. Here we will introduce the extension method. First, we will create a CS file to implement the student class:
Public class student
{
Public student (){}
Public string name {Get; set ;}
Public int age {set; get ;}
Public student (string name, int age)
{
This. Age = age;
This. Name = Name;
}
}
After compilation, this file will form a DLL. We will implement the Code on the background page of aspx:
Static class exstudent // This must be a static class
{
Public static int getage (this student st) {return st. Age };
}
In this way, the methods of the student class are successfully extended. The getage () method can be used as follows:
Student ST = new student ("AA", 12 );
St. getage ();