程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 事件委托案例

C# 事件委托案例

編輯:C#入門知識

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


namespace TDelegate
{

    public delegate void MyHandler1(object sender, MyEventArgs e);
    public delegate void MyHandler2(object sender, MyEventArgs e);


    public class Program
    {


        public static void Main()
        {

            B b = new B();
            A a = new A(b);

            MyEventArgs e1 = new MyEventArgs();
            MyEventArgs e2 = new MyEventArgs();

            e1.m_id = "Event args for event 1";
            e2.m_id = "Event args for event 2";

            b.FireEvent1(e1);
            b.FireEvent2(e2);

            Console.ReadKey();
        }
    }

    class A
    {

        public A(B b)
        {
            b.Event1 += new MyHandler1(OnHandler1);
            b.Event2 += new MyHandler2(OnHandler2);
        }

        public const string m_id = "Class A";

        public void OnHandler1(object sender, MyEventArgs e)
        {
            Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", e.m_id);
        }

        public void OnHandler2(object sender, MyEventArgs e)
        {
            Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id);
        }



    }

    class B
    {

        public event MyHandler1 Event1;
        public event MyHandler2 Event2;

        public void FireEvent1(MyEventArgs e)
        {
            if (Event1 != null)
            {
                Event1(this, e);
            }
        }

        public void FireEvent2(MyEventArgs e)
        {
            if (Event2 != null)
            {
                Event2(this, e);
            }
        }
    }


    public class MyEventArgs
    {
        public string m_id;
    }




}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved