C# Callback思维

方式一、用委托作为形参,把结果传回实参
方式二、通过接口实现
方式三、通过事件关联,适用桌面应用程序
方式四、子窗体调用父窗体的函数(委托)


 

方式一、用委托作为形参,把结果传回实参

public partial class index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Child chld = new Child();
        chld.GetURL((url) =>
        {
            Response.Write(url);
            //取得结果:http://microsoft-zh.cn
        });
    }
}
public class Child
{
    //创建委托
    public delegate void GetURLDelegate(string url);
    public void GetURL(GetURLDelegate func)
    {
        func("http://microsoft-zh.cn");
    }
}

 方式二、通过接口实现

public partial class index : System.Web.UI.Page, ILoginCallback
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Child chld = new Child();
        chld.GetURL(this);
    }
    public void OnGetURL(string url)
    {
        Response.Write(url);
        //取得结果:http://microsoft-zh.cn
    }
}
public class Child
{
    public void GetURL(ILoginCallback callback)
    {
        callback.OnGetURL("http://microsoft-zh.cn");
    }
}

public interface ILoginCallback
{
    /// <summary>
    /// 接口函数
    /// </summary>
    void OnGetURL(string url);
}

方式三、通过事件关联,适用桌面应用程序

public partial class Form1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    Form2 chld = new Form2();
    protected void Button1_Click(object sender, EventArgs e)
    {
        chld.AuthReady += new AuthEventHandler(chld.OnAuthReady);
    }
}
public partial class Form2 : System.Web.UI.Page
{
    // 事件
    public event AuthEventHandler AuthReady;
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (AuthReady != null)
        {
            AuthEventArgs args = new AuthEventArgs();
            args.user_id = 1;
            args.user_name = "micro";
            AuthReady(this, args);
        }
    }
    public void OnAuthReady(object sender, AuthEventArgs e)
    {
        Console.Write(e.user_name);
    }
}
//委托事件
public delegate void AuthEventHandler(object sender, AuthEventArgs e);
public class AuthEventArgs : EventArgs
{
    public int user_id { get; set; }
    public string user_name { get; set; }
}

方式四、子窗体调用父窗体的函数(委托)
1、子窗体Form2

public partial class Form2 : Form
{
    // 申明委托,与父窗体方法类型相同
    public delegate string FunDelegate(int a);
    // 用来接收父窗体方法的委托变量
    public FunDelegate funDelegate;
    private void button1_Click(object sender, EventArgs e)
    {
        if (funDelegate != null)
        {
            // 调用方法
            funDelegate(2);
        }
    }
}

 2、父窗体Form1

private void Form1_Load(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    //父窗体的方法传给子窗体
    frm2.FunDelegate = Fun; 
    frm2.Show();
}
// 父窗体的方法
private string Fun(int a)
{
    return "我是主窗体方法";
}

  


  

 

posted @ 2018-08-17 14:52  microsoftzhcn  阅读(5991)  评论(0编辑  收藏  举报