LINQ

Sử dụng delegate trong C#

Delegate là kỹ thuật giúp chúng ta tạo ra mặt nạ các phương thức.

Tạo ra mặt nạ Delegate đại diện cho 1 tập phướng thức mà các phương thức này không quan tâm đến tên các phương thức.Mà ta chỉ quan tâm các phương thức này có cùng kiểu dữ liệu.

Delegate là tập hợp các phương thức tương đồng kiểu dữ liệu và các đối số truyền vào.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace @delegate

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        { 

        }

        public delegate int changeIn(int x);

       

        public int Nhan2(int x)

        {

            return x * 2;

        }

        public int chia2(int x)

        {

            return x / 2;

        }

        private void button1_Click(object sender, EventArgs e)

        {

            changeIn d = new changeIn(Nhan2);

            lbhienthi.Text = d(2).ToString();          

        }

    }

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;//contronlistbox nên phải new lên

namespace delegate1

{

    public static class Myextencoin

    {

        public delegate bool Matna(int x);

        // bất kỳ hàm nào đối số truyền vào là int  kiểu tra về bool là đúng hay sai.

        public static void tomaulist(this ListBox lst, Matna mn)// mặt nạ là thành 1 kiểu dữ liệu dạng hàm

        {

            lst.SelectedIndex = -1;

            for (int i = 0; i <lst.Items.Count; i++)

            {

                int x = Convert.ToInt32(lst.Items[i]);

                // nếu mặt nạ x= true thõa thì ta tô màu

                // ko quan tâm tên hàm chỉ quam tâm mặt nạ định dạng đúng

                if (mn(x)== true)

                {

                    lst.SelectedIndex = i;

                }

            }