• [自学问题总结]委托与事件


    委托,通熟易懂的举个例子:妈妈让小新去买东西

    一 首先是C#语法

    public delegate void BuyThingEventHandler();

    delegate是关键字

    EventHandler是一个声明委托的微软C#的命名标准

    二 定义小新类

    /// <summary>
    /// 小新类
    /// </summary>
    private class CraYon
    {
    	public static void BuyThing()
    	{
    		Console.WriteLine("妈妈,东西买好了!");
    	}
    }


    三 主方法

    internal class Program
    	{
    		public delegate void BuyThingEventHandler();
    
    		private static void Main(string[] args)
    		{
    			BuyThingEventHandler myDelegate = new BuyThingEventHandler(CraYon.BuyThing);
    
    			myDelegate();
    			Console.ReadKey();
    		}
    	}
    BuyThingEventHandler myDelegate = new BuyThingEventHandler(CraYon.BuyThing);这个是委托声明方法。
    注:委托的参数和返回值类型,都要和具体委托的方法一致:

    public delegate void BuyThingEventHandler();


    public static void BuyThing(){
    Console.WriteLine("妈妈,东西买好了!");

    }

    四 委托链

    简单描述为,妈妈让小新去买完东西后,还让他带小白去散步。

    using System;
    
    namespace test1
    {
    	internal class Program
    	{
    		public delegate void BuyThingEventHandler();
    
    		private static void Main(string[] args)
    		{
    			//委托
    			BuyThingEventHandler myDelegate = new BuyThingEventHandler(CraYon.BuyThing);
    			myDelegate += CraYon.WalkDog;
    
    			myDelegate();
    			Console.ReadKey();
    		}
    	}
    
    	/// <summary>
    	/// 小新类
    	/// </summary>
    	public class CraYon
    	{
    		public static void BuyThing()
    		{
    			Console.WriteLine("妈妈,东西买好了!");
    		}
    
    		public static void WalkDog(){
    			Console.WriteLine("妈妈,小狗散完步了,收集的大便给你!");
    		}
    	}
    }

    其实我们只是在程序中加了
    myDelegate += CraYon.WalkDog;
    这个委托就相当于做了两件事,先买东西再带小白散步。

  • 相关阅读:
    html5之缩放图标
    html5之图片的缩放scale
    html5之打地鼠100%胜率
    html5之调整旋转中心点
    html5之三角旋转
    html5中模块居中
    html5中2d图片旋转
    html5之动态移动图
    html5之steps
    读微信开放文档未解记录
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3196814.html
Copyright © 2020-2023  润新知