C# delegate (001)

时间:2024-04-09 17:36:57

背景:一直不是很理解C#中的委托,也不是很清楚委托应用的业务场景,有可能和自己一直做B/S有关

业务描述:C/S,父窗口打开子窗口,子窗口把自己文本框里的值传个父窗口的文本框.

子窗体代码:

//定义委托
       public delegate void DelegateSetText(string returnValue);
       //生明变量
       public DelegateSetText SetText;
       private void btnClose_Click(object sender, EventArgs e)
       {
          //调用
          SetText(this.txtReturn.Text.Trim());
          this.Close();
       }

父窗体:

private void btnOpen_Click(object sender, EventArgs e)
        {
            frmChild fc = new frmChild();
            //委托调用那个方法
            fc.SetText += new frmChild.DelegateSetText(SetValue);
            fc.Show();
        }

public void SetValue(string strValue)
        {
            this.txtName.Text = strValue;
        }

写完之后有点明白了.

委托的调用步骤(3步):

//定义委托

public delegate int DelegateAdd(int a,int b);

//声明变量
        public DelegateAdd AddMax = new DelegateAdd(Max);
        public DelegateAdd AddMin = new DelegateAdd(Min);
        protected void Button1_Click(object sender, EventArgs e)
        {
           //调用

    Response.Write(AddMax(1, 2).ToString());
           Response.Write(AddMin(1, 2).ToString()) ;
        }

private static int Max(int a, int b)
        {
            return 1;
        }

private static int Min(int a, int b)
        {
            return 2;
        }