Pass Method as Parameter using C#

后端 未结 12 1370
不知归路
不知归路 2020-11-21 23:30

I have several methods all with the same parameter types and return values but different names and blocks. I want to pass the name of the method to run to another method tha

12条回答
  •  孤独总比滥情好
    2020-11-22 00:24

    Here is an example Which can help you better to understand how to pass a function as a parameter.

    Suppose you have Parent page and you want to open a child popup window. In the parent page there is a textbox that should be filled basing on child popup textbox.

    Here you need to create a delegate.

    Parent.cs // declaration of delegates public delegate void FillName(String FirstName);

    Now create a function which will fill your textbox and function should map delegates

    //parameters
    public void Getname(String ThisName)
    {
         txtname.Text=ThisName;
    }
    

    Now on button click you need to open a Child popup window.

      private void button1_Click(object sender, RoutedEventArgs e)
      {
            ChildPopUp p = new ChildPopUp (Getname) //pass function name in its constructor
    
             p.Show();
    
        }
    

    IN ChildPopUp constructor you need to create parameter of 'delegate type' of parent //page

    ChildPopUp.cs

        public  Parent.FillName obj;
        public PopUp(Parent.FillName objTMP)//parameter as deligate type
        {
            obj = objTMP;
            InitializeComponent();
        }
    
    
    
       private void OKButton_Click(object sender, RoutedEventArgs e)
        {
    
    
            obj(txtFirstName.Text); 
            // Getname() function will call automatically here
            this.DialogResult = true;
        }
    

提交回复
热议问题