C # implement and call custom extension methods

Source: Internet
Author: User
Define and call extension methods
  1. Define a static class to include the extension method. This class must be visible to the client code.

  2. Implement the extension method as a static method and make it have at least the same visibility as the inclusion class.

  3. The first parameter of the method specifies the type of operation performed by the method. The parameter must start with the this modifier.

  4. In the call code, add a using command to specify the namespace containing the extension method class.

  5. Call the Extension Method in the same way as the instance method on the call type.

    Note that the first parameter is not specified by the call code because it represents the type of the operator being applied and the compiler knows the object type. You only needNProvide real parameters for the two parameters.

Custom extension methods

  • Namespace lcctest
    {
    Public static class test
    {
    /// <Summary>
    ///
    /// </Summary>
    /// <Param name = "sd"> </param>
    /// <Param name = "id"> </param>
    /// <Param name = "value"> </param>
    /// <Param name = "test"> </param>
    /// <Returns> </returns>
    Public static string TestHelper (this object sd, string id, string value, string test)
    {
    Return "successful ";
    }
    }

    }
  • Call
  • Using lcctest; // reference the namespace
    Namespace MvcApplication1.Controllers
    {
    Public class test
    {
    Public void test1 ()
    {
    String sd;
    Sd. TestHelper ();
    }
    }
    }
  • 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.