开发者

C# - Anonymous delegate

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

namespace Test
开发者_开发百科{
    public delegate void MyDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            DelegateTest tst = new DelegateTest();
            tst.Chaining();
            Console.ReadKey(true);
        }
    }

    class DelegateTest
    {
        public event MyDelegate del;

        public void Chaining()
        {
            del += delegate { Console.WriteLine("Hello World"); };
            del += delegate { Console.WriteLine("Good Things"); };
            del += delegate { Console.WriteLine("Wonderful World"); };
            del();
        }
    }
}


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.


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


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();
    }
}


Yes, they are anonymous delegates (or, more specific, delegates calling an anonymous method).


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜