C# - Anonymous delegate

前端 未结 7 1808
有刺的猬
有刺的猬 2021-02-07 08:00

Like Anonymous Methods ,the delegates i am declaring down using \"delegate\" keyword are anonymous delegates?

namespace Test
{
    public delegate void MyDelegat         


        
相关标签:
7条回答
  • 2021-02-07 08:16

    Your delegate is not anonymous. It's called MyDelegate. Delegate in CLR is a class that derives from System.MulticastDelegate and in your case it's called MyDelegate. You cannot directly derive from MulticastDelegate, C# compiler will stop you.

    In your code when you assign delegates to del, the type/name of the delegate is inferred by compiler because you declared del as event of type MyDelegate.

    0 讨论(0)
  • 2021-02-07 08:17

    There's no such thing as an "anonymous delegate" (or rather, that's not a recognised term in the C# specification, or any other .NET-related specification I'm aware of).

    There are anonymous functions which include anonymous methods and lambda expressions.

    Your code shows plain old anonymous methods - although they are using the one feature lambda expressions don't have: the ability to not express the parameters at all when you don't care about them.

    0 讨论(0)
  • 2021-02-07 08:21

    That's correct, you have assigned a number of anonymous methods to an event.

    If you're using a newer version of c#, you can also do something similar with lambdas. for example:

    class DelegateTest
    {
        public event Action del;
    
        public void Chaining()
        {
            del += () => Console.WriteLine("Hello World");
            del += () => Console.WriteLine("Good Things");
            del += () => Console.WriteLine("Wonderful World");
            del();
        }
    }
    
    0 讨论(0)
  • 2021-02-07 08:22

    Yes. Anonymous delegates cannot be referred to directly by name, so using the delegate(){} syntax means they are anonymous.

    0 讨论(0)
  • 2021-02-07 08:23

    They are delegates to anonymous methods. This is one way to make anonymous methods, which was available since .NET 2.0. With .NET 3.0 you can also use lambda expressions which are simpler to write (but compile to the same code). I suppose that's what you meant with "anonymouse methods". But really, they are one and the same thing.

    0 讨论(0)
  • 2021-02-07 08:26

    Your delegate collection in the example points to a number of anonymous methods. A delegate is "just a method pointer". It doesn't matter if it points to a real method or an anonymous method.

    Please see http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx

    0 讨论(0)
提交回复
热议问题