Passing a callback function to another class

前端 未结 7 1383
小鲜肉
小鲜肉 2021-01-30 00:39

I\'m basically trying to pass a method to another class to be called later, but can\'t quite figure this out in C# (I\'m still too used to Objective-C).

public c         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 01:10

    You could use only delegate which is best for callback functions:

    public class ServerRequest
    {
        public delegate void CallBackFunction(string input);
    
        public void DoRequest(string request, CallBackFunction callback)
        {
            // do stuff....
            callback(request);
        }
    }
    

    and consume this like below:

    public class Class1
        {
            private void btn_click(object sender, EventArgs e)
            {
                ServerRequest sr = new ServerRequest();
                var callback = new ServerRequest.CallBackFunction(CallbackFunc);
                sr.DoRequest("myrequest",callback);
            }
    
            void CallbackFunc(string something)
            {
    
            }
    
    
        }
    

提交回复
热议问题