C# 委托

    委托(Delegate)是存有对某个方法的引用的一种引用类型变量,引用可在运行时被改变。委托(Delegate)特别用于实现事件和回调方法,所有委托(Delegate)都派生于System.Delegate类。(方法被当作方法的参数调用)

注意哦:C#中的委托(Delegate)类似于C或C++中函数的指针。

1、声明委托

委托声明决定了可由该委托引用的方法,委托可指向一个与其具有相同标签的方法。假设

public delegate int DelegateStr (string s);

这个委托可被用于任何一个带有一个单一的string参数的方法,并返回一个int类型变量。声明委托的语法如下:

delegate <return type> <delegate-name> <parameter list>

2、实例化委托以及应用

声明了委托类型,委托对象必须使用new关键字来创建,且与一个特定的方法有关,当创建委托时,传递到new语句的参数就像方法调用一样书写,但是不带有参数。

public delegate void BuyTicketDelegateEvent();
BuyTicketDelegateEvent delegateJay = new BuyTicketDelegateEvent(Wwo.BuyTicket);
BuyTicketDelegateEvent delegateGrape = new BuyTicketDelegateEvent(Wwo.BuyMoveTicket);

下面的实例演示了委托的声明、实例化和使用

namespace Delegate_Practise
{
    public partial class Form1 : Form
    {
        public static string str;
        public static string str2;
        public delegate void BuyTicketDelegateEvent();
        public Form1()
        {
            InitializeComponent();
            //创建委托实例
            BuyTicketDelegateEvent delegateJay = new BuyTicketDelegateEvent(Wwo.BuyTicket);
            BuyTicketDelegateEvent delegateGrape = new BuyTicketDelegateEvent(Wwo.BuyMoveTicket);
            //使用委托对象调用方法
            delegateJay();
            delegateGrape();
            richTextBox1.Text = str + "\r\n" + str2 ;
        }
        public class Wwo
        {
            public static void BuyTicket()
            {
               str = "我喜欢听纠结伦的歌诶";
            }
            public static void BuyMoveTicket()
            {
                str2 = "还喜欢葡萄不愤怒乐队!!!";
            }
        }

    }
}

运行结果:

3、委托的多播(Multicasting of a Delegate)

      委托对象可以使用“+”运算符合并,一个合并委托可以调用它所合并的两个委托。(注意哦:只有相同类型的委托可被合并)“-”运算符可用于从合并的委托中移除组件委托。

namespace Delegate_Practise
{
    public partial class Form1 : Form
    {
        delegate int Numberarithmetic(int W);
        public Form1()
        {
            InitializeComponent();
            // 创建委托实例
            Numberarithmetic Add = new Numberarithmetic(AddNum);
            Numberarithmetic Mult = new Numberarithmetic(MultNum);
            Numberarithmetic Arithemtic;
            Arithemtic = Add;
            Arithemtic += Mult;
            // 调用多播
            Arithemtic(4);
            richTextBox1.Text = $"Value of Num: {getNum()}";
        }
        static int num = 10;
        public static int AddNum(int o)
        {
            num += o;
            return num;
        }

        public static int MultNum(int o)
        {
            num *= o;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
    }
}

运行结果:

(对委托不是很了解,看了一些文章,学习并整理了一下,写得有些拙劣,但也希望能有帮助到!!!) 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值