Can someone distill into proper English what a delegate is?

前端 未结 11 1029
被撕碎了的回忆
被撕碎了的回忆 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: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();
    

提交回复
热议问题