Can someone distill into proper English what a delegate is?

前端 未结 11 1019
被撕碎了的回忆
被撕碎了的回忆 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 03:49

    In the simplest possible terms, it's essentially a pointer to a method.

    You can have a variable that holds a delegate type (just like you would have an int variable that can hold an int type). You can execute the method that the delegate points to by simply calling your variable like a function.

    This allows you to have variable functions just like you might have variable data. Your object can accept delegates from other objects and call them, without having to define all the possible functions itself.

    This comes in very handy when you want an object to do things based on user specified criteria. For example, filtering a list based on a user-defined true/false expression. You can let the user specify the delegate function to use as a filter to evaluate each list item against.

    0 讨论(0)
  • 2020-12-03 03:52

    It's interesting that no-one has mentioned one of key benefits of delegation - it's preferable to sub-classing when you realise that inheritance is not a magic bullet and usually creates more problems than it solves. It is the basis of many design patterns, most notably the strategy pattern.

    0 讨论(0)
  • 2020-12-03 03:56

    A delegate is a pointer to a method. You can then use your delegate as a parameter of other methods.

    here is a link to a simple tutorial.

    The question I had was 'So, why would I want to do that?' You won't really 'get it' until you solve a programming problem with them.

    0 讨论(0)
  • 2020-12-03 03:57

    In the most basic terms, a delegate is just a variable that contains (a reference to) a function. Delegates are useful because they allow you to pass a function around as a variable without any concern for "where" the function actually came from.

    It's important to note, of course, that the function isn't being copied when it's being bundled up in a variable; it's just being bound by reference. For example:

    class Foo
    {
        public string Bar
        {
            get;
            set;
        }
    
        public void Baz()
        {
            Console.WriteLine(Bar);
        }
    }
    
    Foo foo = new Foo();
    Action someDelegate = foo.Baz;
    
    // Produces "Hello, world".
    foo.Bar = "Hello, world";
    someDelegate();
    
    0 讨论(0)
  • 2020-12-03 03:58

    It simply references a method. They come in great use with working with cross threading.

    Here is an example right out of my code.

     //Start our advertisiment thread
        rotator = new Thread(initRotate);
        rotator.Priority = ThreadPriority.Lowest;
        rotator.Start();
    
        #region Ad Rotation
        private delegate void ad();
        private void initRotate()
        {
            ad ad = new ad(adHelper);
            while (true)
            {
                this.Invoke(ad);
                Thread.Sleep(30000);
            }
    
        }
    
        private void adHelper()
        {
            List<string> tmp = Lobby.AdRotator.RotateAd();
            picBanner.ImageLocation = @tmp[0].ToString();
            picBanner.Tag = tmp[1].ToString();            
        }
        #endregion
    

    If you didnt use a delegate you wouldn't be able to crossthread and call the Lobby.AdRotator function.

    0 讨论(0)
  • 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)
    0 讨论(0)
提交回复
热议问题