之前在asp.net 1.1的页面上会有一个页面事件注册的方法
protected override void OnInit(EventArgs e)
{
this.Load += new EventHandler(Page_Load);
base.OnInit(e);
}
asp.net 2.0 中 **.aspx.cs 和 **.aspx.design.cs里面都没有。考虑应该已经在框架内部实现了。
所以找到源代码看了一下。在TemplateControler.cs里面有如下代码
Code
static string [] methodNames = { "Page_Init",
#if NET_2_0
"Page_PreInit",
"Page_PreLoad",
"Page_LoadComplete",
"Page_PreRenderComplete",
"Page_SaveStateComplete",
"Page_InitComplete",
#endif
"Page_Load",
"Page_DataBind",
"Page_PreRender",
"Page_Disposed",
"Page_Error",
"Page_Unload",
"Page_AbortTransaction",
"Page_CommitTransaction"};
看名字很熟悉把。原来已经约定俗成在这里了。
继续查找 methodNames
Code
private ArrayList CollectAutomaticEventInfo () {
ArrayList events = new ArrayList ();
foreach (string methodName in methodNames) {
MethodInfo method = null;
Type type;
for (type = GetType (); type.Assembly != _System_Web_Assembly; type = type.BaseType) {
method = type.GetMethod (methodName, bflags);
if (method != null)
break;
}
if (method == null)
continue;
if (method.DeclaringType != type) {
if (!method.IsPublic && !method.IsFamilyOrAssembly &&
!method.IsFamilyAndAssembly && !method.IsFamily)
continue;
}
if (method.ReturnType != typeof (void))
continue;
ParameterInfo [] parms = method.GetParameters ();
int length = parms.Length;
bool noParams = (length == 0);
if (!noParams && (length != 2 ||
parms [0].ParameterType != typeof (object) ||
parms [1].ParameterType != typeof (EventArgs)))
continue;
int pos = methodName.IndexOf ("_");
string eventName = methodName.Substring (pos + 1);
EventInfo evt = type.GetEvent (eventName);
if (evt == null) {
/**//* This should never happen */
continue;
}
EvtInfo evinfo = new EvtInfo ();
evinfo.method = method;
evinfo.methodName = methodName;
evinfo.evt = evt;
evinfo.noParams = noParams;
events.Add (evinfo);
}
return events;
}
反射获取方法后。经过一系列的检查。然后注册到事件上。
放在内部实现挺好。页面上的代码更简洁了。不过如果不了解页面执行流程的话估计很难理解了。
微软的东西 入门简单。这么处理使用起来的确简单了很多。不过需要记住哪个事件对应哪个名称。
时间仓促,未来得及仔细察看如有错误还请批评指正。