Callbacks in C#

后端 未结 5 1397
孤独总比滥情好
孤独总比滥情好 2020-12-28 17:52

I want to have a library that will have a function in it that accepts an object for it\'s parameter.

With this object I want to be able to call a specified function

5条回答
  •  醉梦人生
    2020-12-28 18:23

    You can use System.Action available in C#.NET for callback functions. Please check this sample example:

        //Say you are calling some FUNC1 that has the tight while loop and you need to 
        //get updates on what percentage the updates have been done.
        private void ExecuteUpdates()
        {
            Func1(Info => { lblUpdInfo.Text = Info; });
        }
    
        //Now Func1 would keep calling back the Action specified in the argument
        //This System.Action can be returned for any type by passing the Type as the template.
        //This example is returning string.
        private void Func1(System.Action UpdateInfo)
        {
            int nCount = 0;
            while (nCount < 100)
            {
                nCount++;
                if (UpdateInfo != null) UpdateInfo("Counter: " + nCount.ToString());
                //System.Threading.Thread.Sleep(1000);
            }
        }
    

提交回复
热议问题