C # Use lambda expressions to pass functions as parameters or attributes across classes

Source: Internet
Author: User

During coding, since we started to perform simple testing and development under winform, we wanted to divide the code into different classes because we had more code, however, because the original test is in the same form, it is very convenient for function calling. Once the cross-class is passed, we will find that the coupling degree of this function is too high, so that I don't know how to decouple it into the class. In this case, you may wish to use the Delegate-type func and action.

Below is the simple code written in winform during the initial test.

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows.Forms;namespace FunctionPass{    public partial class FormMain : Form    {        public FormMain()        {            InitializeComponent();        }        private void buttonTest_Click(object sender, EventArgs e)        {            test();        }        public void test()        {            string sourceStr = collectData();            string digitStr = fetchDigit(sourceStr);            MessageBox.Show("source:" + sourceStr + "\r\n digit:" + digitStr);        }        public string collectData()        {            return Guid.NewGuid().ToString();        }        public string fetchDigit(string sourceStr)        {            Regex regex = new Regex(@"\d*");            MatchCollection digitCollection=regex.Matches(sourceStr);            string digitStr = "";            foreach (Match digitMatch in digitCollection)        {                digitStr += digitMatch;        }                       return digitStr;        }    }}

Here we use the colloectdata function to collect data, extract the numbers in the data through fetchdigit, and then use the test function to display the results.

Now I want to make the display result into a separate class (such as the test class) for better extension.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace FunctionPass{    public class Test    {        public void test()        {            string sourceStr = collectData();            string digitStr = fetchDigit(sourceStr);            MessageBox.Show("source:" + sourceStr + "\r\n digit:" + digitStr);        }    }}

What should I do if collectdata and fetchdigit are not defined? We can pass through a delegate type attribute. The modified code is as follows.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace FunctionPass{    public class Test    {        public Func<string> collectData { get; set; }        public Func<string,string> fetchDigit { get; set; }        public void test()        {            string sourceStr = collectData();            string digitStr = fetchDigit(sourceStr);            MessageBox.Show("source:" + sourceStr + "\r\n digit:" + digitStr);        }    }}

So how can we transfer the collectdata and fetchdigit functions in form? You can assign values directly in form just like assigning values to attributes. The Code is as follows:

Private test _ = new test (); // create an instance private void buttontest_click (Object sender, eventargs e) {test _. collectdata = collectdata; // value: Test _. fetchdigit = fetchdigit; // value test _. test ();}

Now, we want to separate the collectdata and fetchdigit functions from form into a class, so we create a class, such as datadeal. The Code is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;namespace FunctionPass{    public class DataDeal    {        public string collectData()        {            return Guid.NewGuid().ToString();        }        public string fetchDigit(string sourceStr)        {            Regex regex = new Regex(@"\d*");            MatchCollection digitCollection = regex.Matches(sourceStr);            string digitStr = "";            foreach (Match digitMatch in digitCollection)            {                digitStr += digitMatch;            }            return digitStr;        }    }}

In this case, the values of test _. collectdata and test _. fetchdigit in the buttontest_click method in form must be changed. The code after replacement is as follows.

Private test _ = new test (); // create an instance private datadeal _ = new datadeal () to call and pass (); // create an instance private void buttontest_click (Object sender, eventargs e) {test _. collectdata = datadeal _. collectdata; test _. fetchdigit = datadeal _. fetchdigit; test _. test ();}

The code runs successfully.

Some other operations in collectdata and fetchdigit of the datadeal class may cause exceptions. For example, the delegate of the instance method cannot have the null "This"
In this case, the assignment process in form needs to be processed. This can be implemented through lambda expressions. The modified code is as follows.

test_.collectData = () => { return dataDeal_.collectData(); };            test_.fetchDigit = (sourceStr) => { return dataDeal_.fetchDigit(sourceStr); };

Therefore, the function transfer between classes is actually an operation on the attribute, but the type is changed to a delegate type such as func and action.

Note the following:

Func is used to return values.

Action is used without return values.

Reprinted please indicate the source http://blog.csdn.net/xxdddail/article/details/9849111

Related Article

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.