. net extension methods

Source: Internet
Author: User

Conditions that the extension method needs to meet

1. The extension method must be defined in a static class.

2. The extension method must be a static method.

3. The first parameter of an extension method is prefixed with the This modifier.

4. The extension method must be within the extension method of the class that uses it, otherwise the namespace where the using extension method must be displayed.

5, extension methods can only be called by the object.

6. Extension methods under other namespaces have a lower priority than the current namespace extension method.

7. After the extension method is complete, it must be regenerated once before there is a code hint.

To write an example, in MVC3, write a htmlhelper include extension method, introduce the code of an HTML page to the current page.

First create a static class, and then write the extension method:

namespace mvc_ajaxtest{public    static class Exten    {public        static string Include (this htmlhelper htmlhelper , string path)//extension HtmlHelper class        {            string physicalpath = System.Web.HttpContext.Current.Server.MapPath (path);            String str = File.readalltext (physicalpath);            return str; Return the read to the string}}}    

Then create a new text.htm code in the root directory as follows:

<div style= "background:red" > Are you all right in your hometown? </div>

View Code:

@using MVC_AjaxTest@Html.Raw (@Html. Include ("/text.htm"));

To @html.raw () is to prevent the output is HTML encoding, so that the source code as text output without explaining the HTML, the browser display code as follows:

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.