What is a callback?

前端 未结 11 1412
鱼传尺愫
鱼传尺愫 2020-11-28 00:57

What\'s a callback and how is it implemented in C#?

11条回答
  •  庸人自扰
    2020-11-28 01:23

    Definition

    A callback is executable code that is passed as an argument to other code.

    Implementation

    // Parent can Read
    public class Parent
    {
        public string Read(){ /*reads here*/ };
    }
    
    // Child need Info
    public class Child
    {
        private string information;
        // declare a Delegate
        delegate string GetInfo();
        // use an instance of the declared Delegate
        public GetInfo GetMeInformation;
    
        public void ObtainInfo()
        {
            // Child will use the Parent capabilities via the Delegate
            information = GetMeInformation();
        }
    }
    

    Usage

    Parent Peter = new Parent();
    Child Johny = new Child();
    
    // Tell Johny from where to obtain info
    Johny.GetMeInformation = Peter.Read;
    
    Johny.ObtainInfo(); // here Johny 'asks' Peter to read
    

    Links

    • more details for C#.

提交回复
热议问题