用反射方法使用户控件动态调用父页面的方法

下面演示了用户控件调用父页面SetLaeble方法。
父页面类型用反射的方法获取,这避免了不同页面调用同样时,需要类型转换的问题(不用写很多case了:))。

当然还有一种方法是父页面去实现一个接口,即去实现SetLabel方法,uc把this.Page转成这个接口就可以了。


用户控件:

using System.Reflection;
private void Button1_Click(object sender, System.EventArgs e)
        {
            //用反射方法动态调用父页面的方法
            System.Web.UI.Page p = this.Page;
            Type pageType = p.GetType();
            MethodInfo mi = pageType.GetMethod("SetLabel");
            mi.Invoke(p,new object[]{"你这个大猪猪!"});
           
        }

父页面:

public void SetLabel(string str)
        {
            this.Label1.Text = str;
        }

原文:http://www.cnblogs.com/godwar/archive/2007/12/08/988057.html

原文地址:https://www.cnblogs.com/flycantus/p/1289893.html