关于lambda的一个小例子

本文通过一个简单的C#示例介绍了如何使用事件和委托。发布器类定义了一个名为DeliverNewspaper的事件,该事件触发时会传递一条消息;订阅器类则订阅了这个事件,并实现了两个事件处理方法,当事件被触发并带有非空消息时,处理方法将输出相应的信息。

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

/// <summary>
    /// 发布器
    /// </summary>
    public class SBY 
    {
        public delegate Boolean isSucceed(string message);

        public event isSucceed DeliverNewspaper;

        public Boolean GetResult(string dn) 
        {
            if(DeliverNewspaper!=null)
            {
                DeliverNewspaper(dn);
                return true;
            }
            else
            {
                return false;
            }
        }
    }

   /// <summary>
    /// 订阅器
    /// </summary>
    public class TestEvent
    {
        static void Main(string[] args)
        {
            SBY sby = new SBY();
            sby.DeliverNewspaper += (message) =>
            {
                if (!string.IsNullOrEmpty(message))
                {
                    Console.WriteLine("A GetData");
                    return true;
                }
                else
                {
                    Console.WriteLine("A don't GetData");
                    return false;
                }
            };

            sby.DeliverNewspaper += (message) =>
            {
                if (!string.IsNullOrEmpty(message))
                {
                    Console.WriteLine("B GetData");
                    return true;
                }
                else
                {
                    Console.WriteLine("B don't GetData");
                    return false;
                }
            };

            sby.GetResult("send the newspaper");
            Console.ReadLine();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值