在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();
}
}
}
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();
}
}
}