Can someone distill into proper English what a delegate is?

前端 未结 11 1057
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 03:27

Can someone please break down what a delegate is into a simple, short and terse explanation that encompasses both the purpose and general benefits? I\'ve tried to wrap my h

11条回答
  •  半阙折子戏
    2020-12-03 04:01

    In most simplest terms, the responsibility to execute a method is delegated to another object. Say the president of some nation dies and the president of USA is supposed to be present for the funeral with condolences message. If the president of USA is not able to go, he will delegate this responsibility to someone either the vice-president or the secretary of the state.

    Same goes in code. A delegate is a type, it is an object which is capable of executing the method.

    eg.

    Class Person
    {
       public string GetPersonName(Person person)
       {
         return person.FirstName + person.LastName;
       }
    
       //Calling the method without the use of delegate
       public void PrintName()
       {
          Console.WriteLine(GetPersonName(this));
       }
    
       //using delegate
       //Declare delegate which matches the methods signature
       public delegate string personNameDelegate(Person person);
    
      public void PrintNameUsingDelegate()
      {
          //instantiate
          personNameDelegate = new personNameDelegate(GetPersonName);
    
          //invoke
          personNameDelegate(this);
      }
    
    }
    

    The GetPersonName method is called using the delegate object personNameDelegate. Alternatively we can have the PrintNameUsingDelegate method to take a delegate as a parameter.

    public void PrintNameUsingDelegate(personNameDelegate pnd, Person person)
    {
       pnd(person);
    }
    

    The advantage is if someone want to print the name as lastname_firstname, s/he just has to wrap that method in personNameDelegate and pass to this function. No further code change is required.

    Delegates are specifically important in

    1. Events
    2. Asynchronous calls
    3. LINQ (as lambda expressions)

提交回复
热议问题