子程序定义:
public delegate void CurrentControlListenEvent(string uniqueID, string way = null); public event CurrentControlListenEvent CurrentControlEvent; protected void InvokeCurrentControlEvent(string uniqueID, string way = null) { if (this.CurrentControlEvent != null) CurrentControlEvent(this.UniqueID); }
子程序调用:
InvokeCurrentControlEvent("123456"); //或 InvokeCurrentControlEvent("123456","del");
父程序定义:
Control ctl = LoadControl("~/UserControls/Metadata/ucAttributeValues.ascx"); ctl.ID = "ucAttributeValues" + (tempLoadPhValueControlCount); Type type = ctl.GetType(); EventInfo currentControlEvent = type.GetEvent("CurrentControlEvent"); Type tDelegate = currentControlEvent.EventHandlerType; MethodInfo miHandler = this.GetType().GetMethod("InvokeControl"); Delegate d = Delegate.CreateDelegate(tDelegate, this, miHandler); MethodInfo addHandler = currentControlEvent.GetAddMethod(); Object[] addHandlerArgs = { d }; addHandler.Invoke(ctl, addHandlerArgs); //正常非反射的调用方式就一行代码,但有些情况不得不用反射来操作委托的实例 //ctl.SetCaptureListener(new UserControls_Metadata_ucAttributeValues.CaptureListenEvent(InvokeControl));
委托子程序调用父程序的方法体:
public void InvokeSubtract(string uniqueID) { if (this.phCtl.Controls.Count > 0) { for (int i = this.phCtl.Controls.Count - 1; i >= 0; i--) { if (phCtl.Controls[i].UniqueID == uniqueID) { phCtl.Controls[i].Visible = false; break; } } } }