委托:主人和仆人的例子

using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;

namespace  AspNetTest.Common
{
    
/// <summary>
    
/// Define_Delegate_Master2Servant 的摘要说明。
    
/// </summary>

    public class Define_Delegate_Master2Servant : System.Web.UI.Page
    
{
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            Master2 master 
= new Master2();
            Servant servant 
= new Servant();
            master.EatEvent 
+= new EatEventHandler(servant.Arrange);
            master.Hungry(
"福州""锅边");
            
// 在此处放置用户代码以初始化页面
        }

        
        
Web 窗体设计器生成的代码
    }

    
    
public class EatEventArgs : EventArgs
    
{
        
public string eatAddress;
        
public string eatContent;
    }

    
public delegate void EatEventHandler(object sender, EatEventArgs e);
    
    
public class Master2
    
{
        
public EatEventHandler EatEvent;
        
private void  OnEatEvent(EatEventArgs e)
        
{
            
if(EatEvent != null)
            
{
                EatEvent(
this, e);
            }

        }

        
public void Hungry(string eatAddress, string eatContent)
        
{
            HttpContext.Current.Response.Write(
"主人:我肚子饿了,我要吃东西!<br>");
            HttpContext.Current.Response.Write(
"主人:地点是 " + eatAddress + "。<br>");
            HttpContext.Current.Response.Write(
"主人:要吃的食物是 " + eatContent + "。<br><hr>");
            EatEventArgs e 
= new EatEventArgs();
            e.eatAddress 
= eatAddress;
            e.eatContent 
= eatContent;
            OnEatEvent(e);
        }

    }

    
    
public class Servant
    
{
        
public void Arrange(object sender, EatEventArgs e)
        
{
            HttpContext.Current.Response.Write(
"仆人:主人,你好,给你做了安排!<br>");
            HttpContext.Current.Response.Write(
"仆人:安排的地点是 " + e.eatAddress + "。<br>");
            HttpContext.Current.Response.Write(
"仆人:安排的食物是 " + e.eatContent + "。<br>");
        }

    }

    
}

你可能感兴趣的:(例子)