实现Asp.Net里的Page页面上的函数可有可无(Page_Init等)

在Asp.net中大家都知道,在一个aspx的代码页中可以定义Page_Init和Page_UnLoad等页面函数,定义了它就会在Page对象中调用事件的时候执行相应的Page函数,没定义就不会执行也不会报错,这是怎么实现的呢,这里我提供一种使用反射的方法来实现:

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

namespace  ReflectionDelegate
{
    
class  Program
    {
        
class  Page
        {
            
public   delegate   void  DelMethod();
            
public   event  DelMethod OnMethod; // 此事件就如同ASP.NET的Page对象里面的OnInit事件

            
public   int  i  =   0 ;

            
public   void  ArouseMethodEvent()
            {
                Type t 
=   this .GetType(); // 在MyPage中调用this.GetType()返回的是实际上是MyPage的Type,因为ArouseMethodEvent是由MyPage的对象调用的,所以这里的this也就是MyPage的对象
                MethodInfo mi  =  t.GetMethod( " method " , BindingFlags.NonPublic  |  BindingFlags.Instance); // 反射是否定义了method函数
                 if  (mi  !=   null )
                {
                    Delegate dtemp 
=  Delegate.CreateDelegate( typeof (Page.DelMethod),  this , mi,  true ); // 创建Page.DelMethod委托实例,并赋给dtemp,其中this表示mi所封装函数method的调用对象,即指定在使用委托实例或事件调用函数method的时候,method中的this代表的是哪个对象 
                     this .OnMethod  +=  dtemp  as  Page.DelMethod; // 因为所有自定义委托都继承自Delgate,所以可以将dtemp as Page.DelMethod

                    
if  ( this .OnMethod  !=   null )
                        
this .OnMethod();
                }
            }
        }

        
class  MyPage : Page
        {
            
protected   void  method() // 此函数就如同ASP.NET的Page对象里面的Page_Init等函数,可有可无
            {
                Console.WriteLine(
" 被事件调用 " );
                Console.WriteLine(
" 其中i= "   +   this .i.ToString()); // 这里的this就是上面调用Delegate.CreateDelegate传入的第二个参数的this
            }
        }


        
static   void  Main( string [] args)
        {
            MyPage page 
=   new  MyPage();
            page.i 
=   100 ;
            page.ArouseMethodEvent();
        }
    }
}

 

 

 

转载于:https://www.cnblogs.com/OpenCoder/archive/2009/11/17/1604795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值