通过一个例子简单几种委托的使用及事件

第一章:

第一种,通过new 关键字创建对象  特别注意:这种方式必须要先有根据委托创建的方法与之关联,否则不能使用。  或者直接让委托变量直接指向某个具体的方法(前提是方法要存在)

格式为:同一命名空间下

   public delegate void One();//无参数也无返回值
 
        
    class Program
    {
        static void Main(string[] args)
        {

            One objOne0= new One(其中必须有方法作为参数);
            One objOne00=必须的方法;

        }
/////书写根据委托对象创建的方法
    }

第二种,匿名函数 

格式为:同一命名空间下

      public delegate void One();//无参数也无返回值
      
     public delegate void Two(string word);有参数但没有返回值

     public delegate string Three(string word);有参数也有返回值
    class Program
    {
        static void Main(string[] args)
        {
            One objOne = delegate () {方法体 };//匿名函数  无参数也无返回值

Two objTwo=delegate(string word){方法体};//有参数无返回值的匿名函数

Three objThree=delegate(string word){return word};//有参数有返回值的匿名函数 } }

第三种,lambda表达式

格式为:在同一命名空间下

 public delegate void One();//无参数也无返回值
    public delegate void Two(string word); //有参数但没有返回值
    public delegate string Three(string word);//有参数也有返回值
        
    class Program
    {
        static void Main(string[] args)
        {
            
            One objOne = () => { };//lambda 表达式 无参数也没有返回值

       
            Two objTWO=(string word)=>{ };//有参数但没有返回值的lambda表达式

     
            Three objThree = (string word) => { return word; };//有参数有返回值的lambda表达式
        }
    }

 泛型集合的lambda表达式:

1.首先创建泛型集合类并初始化

List<int> List = new List<int>(){1,2,3,4,5,6,7};

2,使用lambda表达式删除集合中的元素

list.RemoveAll(n=>n>4);

运行结果为1,2,3,4

第二章:事件

事件的由来

1.什么是事件?

2.事件能做什么?

原文地址:https://www.cnblogs.com/wfaceboss/p/6371744.html