C#中事件(event)和委托(delegate)的使用

本文介绍了C#中事件(event)和委托(delegate)的应用场景。在无法直接访问其他窗体控件时,通过订阅事件来传递参数并执行相应操作。文中提供了一个实例,创建了Monitor类,定义了自定义委托和事件,并在窗体初始化时订阅该事件。在主程序中模拟触发事件,展示了事件触发后执行订阅函数的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用场景

当我们在cs类中给其他窗体中的控件赋值或者设置属性时,因为在cs类中无法获取的其他窗体上的控件,所以通过订阅事件的方式,当事件触发,订阅事件的函数也会执行,此间进行参数传递

实例

新建Monitor类,添加自定义委托和事件,执行事件时参数和委托的参数相同

class Monitor
    {
        //定义委托
        public delegate void DelegateTest(string s);
        //定义事件
        public static event DelegateTest EventTest;

        public void onEventTest(string s)
        {
            if (EventTest != null)
            {
                EventTest(s);
            }
        }
    }

在窗体控件添加文本框控件,并在窗体初始化中订阅事件

public Form1()
        {
            InitializeComponent();
            Monitor monitor = new Monitor();
            //先取消订阅
            Monitor.EventTest -= new Monitor.DelegateTest(changeTextBox);
            //将changeTextBox订阅事件
            Monitor.EventTest += new Monitor.DelegateTest(changeTextBox);
        }

        public void changeTextBox(string s)
        {
            this.textBox1.Text = s;
        }
    }

在主程序中测试,模拟触发自定义事件,触发自定义事件后,会执行订阅此事件的所有函数

static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form aa = new Form1();
            string s = "hello";
            Monitor monitor = new Monitor();
            //判断事件是否为空
            if(onEventTest != null)
            {
                monitor.onEventTest(s);
            }
            Application.Run(aa);
        }

效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值