Use of the proxy method keyword Action and Fun

Source: Internet
Author: User

Proxy is a special method that points to the address of a method module. Generally, the method module can be a common method. More often, it is an anonymous Lambda expression, that is, an anonymous method. Now let's take a brief look at the abbreviated proxy method, that is, the Action keyword.

    class A    {        B b = new B();        public delegate string Show(string result);        public string Execute()        {            Show s = new Show(b.MyShow);            string str = s.Invoke("ttt");            return str;        }    }    class B    {        public string MyShow(string s)        {            return s + ">>>>>>>>>";        }    }    static void Main(string[] args)    {        A a = new A();        a.Execute();    }
In this way, when A is used, only the MyShow code in B is changed, and the execution result of Execute in A can be customized. Code with the same function is completed using the Action type.
    class C    {        D d = new D();        Action
 
   action;        public void Execute()        {            action = d.MyShow2;            action.Invoke("ttt");        }    }    class D    {        public void MyShow2(string s)        {            Console.WriteLine(s + ">>>>>>>>>");        }    }    static void Main(string[] args)    {        A a = new A();        a.Execute();    }
 

This code has the same effect as the above Code. It can be seen that, in essence, Action is the simplified mode of delegate, just like lamda expressions to simplify anonymous methods. When an anonymous method must have a return value, we use the Fun type for processing. Basically, actions are the same in usage. For parameters, the first few are input values, and the last one is the return value.

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.