C #-Extension Method

Source: Internet
Author: User

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 ();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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.