I have example code of delegate in c#. I wan to know can delegate be used as class as the it is shown in the following example:

using System;

// This delegate returns int and takes an int argument.
delegate int CountIt(int end);

class VarCapture {

    static CountIt Counter() {
        int sum = 0;
        // Here, a summation of the count is stored
        // in the captured variable sum.
        CountIt ctObj = delegate (int end) {
            for(int i=0; i <= end; i++) {
                Console.WriteLine(i);
                sum += i;
            }
            return sum;
        };
        return ctObj;
    }

    static void Main() {
        // Get a counter.
        CountIt count = Counter();
        int result;
        result = count(3);
        Console.WriteLine("Summation of 3 is " + result);
        Console.WriteLine();
        result = count(5);
        Console.WriteLine("Summation of 5 is " + result);
    }
} 
有帮助吗?

解决方案

Yes, delegate types are classes - each concrete delegate type inherits from MulticastDelegate, and you can pass around delegate references just like you can pass any other kind of reference.

There are various ways in which they're handled specially, by the CLR, framework and language, but those are extra features on top of what normal classes are capable of.

In this particular case, you're using an anonymous method to create an instance of the delegate. You might want to look into lambda expressions which have generally replaced the use of anonymous methods in idiomatic C#, except in a very few cases.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top