简体   繁体   English

委托可以用作类类型

[英]delegate can be used as class type

I have example code of delegate in c#. 我在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. 是的,委托类型是类-每个具体的委托类型都继承自MulticastDelegate ,并且您可以像传递任何其他类型的引用一样传递委托引用。

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. 有些情况下,他们是特殊处理的,由CLR,框架和语言不同的方式,但这些都是在上面额外的功能什么的正常类是可以胜任的。

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. 您可能要研究通常在惯用C#中已取代匿名方法的lambda表达式 ,但极少数情况除外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM