繁体   English   中英

委托可以用作类类型

[英]delegate can be used as class type

我在C#中有委托的示例代码。 我想知道可以将委托用作类,如以下示例所示:

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

是的,委托类型是类-每个具体的委托类型都继承自MulticastDelegate ,并且您可以像传递任何其他类型的引用一样传递委托引用。

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

在这种情况下,您将使用匿名方法创建委托的实例。 您可能要研究通常在惯用C#中已取代匿名方法的lambda表达式 ,但极少数情况除外。

暂无
暂无

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

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