1. 程式人生 > >C#委託,事件與回撥函式

C#委託,事件與回撥函式

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

namespace TestApp
{
    
///<summary>/// 委託
    
///</summary>///<param name="s1"></param>///<param name="s2"></param>///<returns></returns>publicdelegatevoid ProcessDelegate(object sender, EventArgs e);

    
class Program
    {
        

        
staticvoid Main(string[] args)
        {
            
/*  第一步執行  */
            Test t 
=new Test();
            
/* 關聯事件方法,相當於尋找到了委託人 */
            t.ProcessEvent 
+=new ProcessDelegate(t_ProcessEvent);
            
/* 進入Process方法 */
            Console.WriteLine(t.Process()); 

            Console.Read();
        }

        
staticvoid t_ProcessEvent(object sender, EventArgs e)
        {
            Test t 
= (Test)sender;
            t.Text1 
="Hello";
            t.Text2 
="World";
        }
    }

    
publicclass Test
    {
        
privatestring s1;

        
publicstring Text1
        {
            
get { return s1; }
            
set { s1 
= value; }
        }

        
privatestring s2;

        
publicstring Text2
        {
            
get { return s2; }
            
set { s2 = value; }
        }


        
publicevent ProcessDelegate ProcessEvent;

        
void ProcessAction(object sender, EventArgs e)
        {
            
if (ProcessEvent ==null)
                ProcessEvent 
+=new ProcessDelegate(t_ProcessEvent);
            ProcessEvent(sender, e);
        }

        
//如果沒有自己指定關聯方法,將會呼叫該方法丟擲錯誤void t_ProcessEvent(object sender, EventArgs e)
        {
            
thrownew Exception("The method or operation is not implemented.");
        }

        
void OnProcess()
        {
            ProcessAction(
this, EventArgs.Empty);
        }

        
publicstring Process()
        {
            OnProcess();
            
return s1 + s2;
        }
    }
}