学习c#之委托

class Program
{
//定义委托
delegate bool Function(int num);

    //定义委托逻辑
    static Function GreaterThan10 = delegate(int n){ return n >= 10; };

    //使用委托的方法
    static List<int> Traverse(List<int> nums,Function function
        ) {
        var list = new List<int>();

        foreach (var num in nums) {
            if (function(num)) {
                list.Add(num);
            }
        }

        return list;

    }

    static void Main(string[] args)
    {

        //调用委托
        List<int> nums=Traverse(new List<int>() { 1,2,3,4,5,6,7,11}, GreaterThan10);

        foreach (int num in nums) {
            Console.WriteLine(num);
        }

        Console.Read();

    }
}

在这里插入图片描述
定义委托逻辑
static Function GreaterThan10 = delegate(int n){ return n >= 10; };
可以使用lambda在调用方法时进行简化,如
List nums=Traverse(new List() { 1,2,3,4,5,6,7,11}, n=>n>=10);

在这里插入图片描述
Action 没有返回值的delegate(委托)

Func<输入参数,返回值> 有返回值的delegate(委托)

Predicate 返回值布尔的delegate(委托)

多播委托

方法签名一致的委托可以进行加减,委托会采用链表的方式顺序执行

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
//用户类
class Person {
public string name { get; set; }

    public Newspaper newspaper{set;get;}

    

    public Person(string name) { this.name = name; }

    public void setNewpaper(Newspaper newspaper) {
        this.newspaper = newspaper;
    }

    public void ReadNewpaper() {
        Console.WriteLine("个人{0}正在读报纸,出版社是{3},标题是{1},内容是{2}",this.name,this.newspaper.Title,this.newspaper.Content,this.newspaper.PublisherName);
    }


}

//公司类
class Company
{
    public string name { get; set; }

    public Newspaper newspaper { set; get; }



    public Company(string name) { this.name = name; }

    public void setNewpaper(Newspaper newspaper)
    {
        this.newspaper = newspaper;
    }

    public void ReadNewpaper()
    {
        Console.WriteLine("公司{0}正在读报纸,出版社是{3},标题是{1},内容是{2}", this.name, this.newspaper.Title, this.newspaper.Content, this.newspaper.PublisherName);
    }


}

class Publisher {
    public string Name { set; get; }

    public Publisher(string name) { this.Name = name; }

    //public delegate void _Subscribers(Newspaper newspaper);

    //public _Subscribers Subscribers { set; get; }

    public Action<Newspaper> Subscribers;

    //public List<Person> Persons = new List<Person>();

    public void SendNewspaper(Newspaper newspaper)
    {
        newspaper.PublisherName = Name;
        if (Subscribers!=null) {
            Subscribers(newspaper);
        }

    }

}

//报纸类
class Newspaper {
    public string PublisherName { set; get;}
    public string Title { set; get; }
    public string Content { set; get; }
}



class Program
{
    static Action<int> Print;

    static void Main(string[] args)
    {

        var publisher = new Publisher("出版社");
        var A = new Person("a");
        var B = new Person("b");
        var C = new Person("c");
        var D = new Company("d");
        publisher.Subscribers = A.setNewpaper;
        publisher.Subscribers += B.setNewpaper;
        publisher.Subscribers += C.setNewpaper;
        publisher.Subscribers += D.setNewpaper;
        

        publisher.SendNewspaper(new Newspaper() { Title = "报纸标题",Content  = "报纸内容"});
        D.ReadNewpaper();


        Console.ReadLine();
    }
}

}

在出版社类Publisher 中有SendNewspaper报纸派发方法和Subscribers委托。。SendNewspaper方法中调用委托,在进行报纸派发的时候。
用户和公司存在方法setNewpaper,setNewpaper方法签名与Subscribers一致固能使用委托,且可使用多播委托(链表),之后出版社类Publisher调用SendNewspaper方法处理委托

多播链表异常
 if (Subscribers!=null) {
            Subscribers(newspaper);
        }

这一段代码如果在链表执行时出现异常链表不会继续执行下去,固需要修改为:

if (Subscribers!=null) {
foreach (Action handler in Subscribers.GetInvocationList()) {
try
{
handler(newspaper);
}
catch (Exception e)
{

                    Console.WriteLine(e.Message);
                }
            }
            //Subscribers(newspaper);
        }

存在多个出版社Publisher1,Publisher2的情况下,可以EventHandler Subscribers定义事件(EventHandler等价于 Action<this,PublisherArgs>),
Subscribers判断属于哪一家出版社

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{

class PublisherArgs : System.EventArgs {

    public Newspaper newspaper { set; get; }

    public PublisherArgs(Newspaper newspaper) { this.newspaper = newspaper; }

}


//用户类
class Person
{
    public string name { get; set; }

    public Newspaper newspaper { set; get; }



    public Person(string name) { this.name = name; }

    public void setNewpaper(Object sender, PublisherArgs args)
    {
        if (sender is Publisher1) {
            args.newspaper.PublisherName = (sender as Publisher1).Name;
        }
        if (sender is Publisher2)
        {
            args.newspaper.PublisherName = (sender as Publisher2).Name;
        }

        this.newspaper = args.newspaper;
    }

    public void ReadNewpaper()
    {
        Console.WriteLine("个人{0}正在读报纸,出版社是{3},标题是{1},内容是{2}", this.name, this.newspaper.Title, this.newspaper.Content, this.newspaper.PublisherName);
    }


}

//公司类
class Company
{
    public string name { get; set; }

    public Newspaper newspaper { set; get; }



    public Company(string name) { this.name = name; }

    public void setNewpaper(Object sender, PublisherArgs args)
    {
        if (sender is Publisher1)
        {
            args.newspaper.PublisherName = (sender as Publisher1).Name;
        }
        if (sender is Publisher2)
        {
            args.newspaper.PublisherName = (sender as Publisher2).Name;
        }

        this.newspaper = args.newspaper;
    }

    public void ReadNewpaper()
    {
        Console.WriteLine("公司{0}正在读报纸,出版社是{3},标题是{1},内容是{2}", this.name, this.newspaper.Title, this.newspaper.Content, this.newspaper.PublisherName);
    }


}

class Publisher1
{
    public string Name { set; get; }

    public Publisher1(string name) { this.Name = name; }

    //public delegate void _Subscribers(Newspaper newspaper);

    //public _Subscribers Subscribers { set; get; }

    public event EventHandler<PublisherArgs> Subscribers;

    //public List<Person> Persons = new List<Person>();

    public void SendNewspaper(Newspaper newspaper)
    {
        
        if (Subscribers != null)
        {
            foreach (EventHandler<PublisherArgs> handler in Subscribers.GetInvocationList())
            {
                try
                {
                    handler(this, new PublisherArgs(newspaper));
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }
            }
           
        }

    }

}


class Publisher2
{
    public string Name { set; get; }

    public Publisher2(string name) { this.Name = name; }

    //public delegate void _Subscribers(Newspaper newspaper);

    //public _Subscribers Subscribers { set; get; }

    public event EventHandler<PublisherArgs> Subscribers;

    //public List<Person> Persons = new List<Person>();

    public void SendNewspaper(Newspaper newspaper)
    {

        if (Subscribers != null)
        {
            foreach (EventHandler<PublisherArgs> handler in Subscribers.GetInvocationList())
            {
                try
                {
                    handler(this, new PublisherArgs(newspaper));
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }
            }

        }

    }

}

//报纸类
class Newspaper
{
    public string PublisherName { set; get; }
    public string Title { set; get; }
    public string Content { set; get; }
}



class Program
{
    static Action<int> Print;

    static void Main(string[] args)
    {

        var publisher = new Publisher1("出版社");
        var A = new Person("a");
        var B = new Person("b");
        var C = new Person("c");
        var D = new Company("d");
        publisher.Subscribers += A.setNewpaper;
        publisher.Subscribers += B.setNewpaper;
        publisher.Subscribers += C.setNewpaper;
        publisher.Subscribers += D.setNewpaper;


        publisher.SendNewspaper(new Newspaper() { Title = "报纸标题", Content = "报纸内容" });
        D.ReadNewpaper();


        Console.ReadLine();
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值