zoukankan      html  css  js  c++  java
  • 委托讲解

    C#的委托最经典的解释:
    例子:this.Activated += new EventHandler(Form1_Activated);

    这是一个委托的原理.
    this.Activated=你吃完饭; 事件
    Form1_Activated=喊我一声;方法

    这句话的意思就是把这两个事放在一起了,意思就是叫你吃完饭了喊我一声。我委托你吃完饭了,喊我一声。

    这样我就不用过一会就来看一下你吃完了没有了,已经委托你了

    ——————————————————————————————————————————————————

    EventHandler 委托

    [SerializableAttribute]
    [ComVisibleAttribute(true)]
    public delegate void EventHandler(
    	Object sender,
    	EventArgs e
    )

    参数

    sender 类型:System.Object 事件源。

    e 类型:System.EventArgs 不包含事件数据的对象。

    例子
    using System;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Counter c = new Counter(new Random().Next(10));
                c.ThresholdReached += c_ThresholdReached;
    
                Console.WriteLine("press 'a' key to increase total");
                while (Console.ReadKey(true).KeyChar == 'a')
                {
                    Console.WriteLine("adding one");
                    c.Add(1);
                }
            }
    
            static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
            {
                Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold,  e.TimeReached);
                Environment.Exit(0);
            }
        }
    
        class Counter
        {
            private int threshold;
            private int total;
    
            public Counter(int passedThreshold)
            {
                threshold = passedThreshold;
            }
    
            public void Add(int x)
            {
                total += x;
                if (total >= threshold)
                {
                    ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                    args.Threshold = threshold;
                    args.TimeReached = DateTime.Now;
                    OnThresholdReached(args);
                }
            }
    
            protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
            {
                EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
                if (handler != null)
                {
                    handler(this, e);
                }
            }
    
            public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
        }
    
        public class ThresholdReachedEventArgs : EventArgs
        {
            public int Threshold { get; set; }
            public DateTime TimeReached { get; set; }
        }
    }
    
    
    
    
     
  • 相关阅读:
    ASP.NET MVC 异常捕获
    Jquery 扩展方法
    Spring.NET笔记1
    ASP.NET MVC Ninject 实现依赖注入
    ASP.NET MVC Unity实现依赖注入
    windows service
    反射用法
    抽象工厂核心反射
    (C#)中的DataSet、string、DataTable等对象转换成Json
    .NET批量删除代码前的行号
  • 原文地址:https://www.cnblogs.com/PeaCode/p/3867641.html
Copyright © 2011-2022 走看看