C # Extension methods

Source: Internet
Author: User

The Using system;using system.collections.generic;using system.linq;using system.text;/* * extension method allows you to write and declare methods that are associated with classes outside of its class  * 1, the extension method must be declared as Static * 2, the class where the extension method declaration resides must also be declared as static * 3, the extension method must contain the keyword this as his first argument type, and followed by the name of the class it extends to */ Namespace extendmethod{    Sealed class mydata    {        Private double D1, D2, d3;        public MyData (double d1, double D2, double D3)         {    &N Bsp       D1 = D1; D2 = D2; D3 = d3;       }        public double Sum ()         {  &N Bsp         return D1 + D2 + d3;       }   }    Static class Ext endmydata    {        public static double Average (this MyData MD)//Extension class MyData method   &NBSP ;     {             return MD. Sum ()/3;       }&NBSp  }    Static class extendmydata1    {        public static double Average (M Ydata MD)//non-extended class MyData method         {            return MD. Sum ()/3;       }   }    class program    {      &NBSP ; static void Main (string[] args)         {            MyData MD = new Myda Ta (3, 4, 5);            Console.WriteLine ("Sum: {0}", Md. Sum ());            Console.WriteLine ("extension method Md. Avrage: {0} ", Md. Average ());            Console.WriteLine ("Non-extended method extendmydata1.average:{0}", Extendmydata1.average (MD));            Console.readkey ();       }& nbsp  }}

C # Extension methods

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.