2018年1月24日水曜日

C# delegate

A delegate is like a pointer to a function. It is a reference type data type and it holds the reference of a method.
delegate は代表の意味である。定義と同じ戻り値と引数を持つMethodを代入できる。

class Program
{
    // declare delegate
    public delegate void Print(int value);

    static void Main(string[] args)
    {
        // Print delegate points to PrintNumber
        Print printDel = PrintNumber;
         
        printDel(100000);
        printDel(200);

        // Print delegate points to PrintMoney
        printDel = PrintMoney;

        printDel(10000);
        printDel(200);
    }

    public static void PrintNumber(int num)
    {
        Console.WriteLine("Number: {0,-12:N0}",num);
    }

    public static void PrintMoney(int money)
    {
        Console.WriteLine("Money: {0:C}", money);
    }
}

A method can have a parameter of a delegate type and can invoke the delegate parameter.

public static void PrintHelper(Print delegateFunc, int numToPrint)
{
    delegateFunc(numToPrint);
}

参考:http://www.tutorialsteacher.com/csharp/csharp-delegates

0 件のコメント:

コメントを投稿