委托基础

C# 委托详解

 

1.什么是委托?

委托是一种定义方法签名的类型,可以与具有兼容签名的任何方法关联。

2.委托有什么特点?

委托类似于 C++ 函数指针,但它们是类型安全的。
委托允许将方法作为参数进行传递。
 委托可用于定义回调方法。
委托可以链接在一起;例如,可以对一个事件调用多个方法。
方法不必与委托签名完全匹配。
 C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。
C# 3.0 引入了 Lambda 表达式,利用它们可以更简练地编写内联代码块。匿名方法和 Lambda 表达式(在某些上下文中)都可编译为委托类型。这些功能统称为匿名函数。
3.如何使用委托?

Demo:

using System;

namespace ConsoleApplication28
{
    class Program
    {
        public static void FunctionA(string strMessage)
        {
            Console.WriteLine(strMessage);
        }

        public delegate void DelegateMethod(string strMessage);

        static void Main(string[] args)
        {
            DelegateMethod handler = FunctionA;
            handler("Hello Kevin");
        }
    }
}
4.匿名方法

在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,通过使用匿名方法,由于您不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。以下是两个使用匿名方法的示例:

Demo1:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Click += delegate(object sender, EventArgs e)
            {
                MessageBox.Show("The box is click");
            };
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }
    }
}Demo2:

void StartThread()
        {
            Thread t1 = new Thread
                (delegate()
                {
                    MessageBox.Show("Hello,");
                    MessageBox.Show("Kevin");
                });
            t1.Start();
        }
5.合并委托(多路广播委托)

Demo:

using System;

namespace ConsoleApplication29
{
    delegate void DelegageMethod();
    class Program
    {
        static void A()
        {
            Console.WriteLine("A");
        }

        static void B()
        {
            Console.WriteLine("B");   
        }

        static void Main(string[] args)
        {
            DelegageMethod a, b, c, d;
            a = A;
            b = B;
            c = a + b;
            d = c - a;
            Console.WriteLine("Invoking delegate a:");
            a();
            Console.WriteLine("Invoking delegate b:");
            b();
            Console.WriteLine("Invoking delegate c:");
            c();
            Console.WriteLine("Invoking delegate d:");
            d();
        }
    }
}

 

输出结果:
Invoking delegate a:
A
Invoking delegate b:
B
Invoking delegate c:
A
B
Invoking delegate d:
B

转载于:https://www.cnblogs.com/eagle1986/archive/2010/01/15/1648270.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值