曹永思

导航

Asp.Net 利用反射获得委托和事件以及创建委托实例和添加事件处理程序

子程序定义:

      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;
                    }
                }
            }
        }

 

posted on 2016-06-06 16:39  曹永思  阅读(188)  评论(0编辑  收藏  举报