Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            // Approach 1:
            SampleDelegate1 del1 = new SampleDelegate1(SampleMethodOne);
            SampleDelegate1 del2 = new SampleDelegate1(SampleMethodTwo);
            SampleDelegate1 del3 = new SampleDelegate1(SampleMethodThree);
            // In this example del4 is a multicast delegate. You use +(plus)
            // operator to chain delegates together and -(minus) operator to remove.
            SampleDelegate1 del4 = del1 + del2 + del3 - del2;

            del4();

            // Approach 2:
            // In this example del is a multicast delegate. You use += operator
            // to chain delegates together and -= operator to remove.
            SampleDelegate2 delAp2 = new SampleDelegate2(SampleMethodOne);

            delAp2 += SampleMethodTwo;
            delAp2 += SampleMethodThree;
            delAp2 -= SampleMethodTwo;
            del2();

            // Multicast delegate with an int return type:
            SampleDelegate3 delAp3 = new SampleDelegate3(SampleMethodOneInt);

            delAp3 += SampleMethodTwoInt;


            // The ValueReturnedByDelegate will be 2, returned by the SampleMethodTwo(),
            // as it is the last method in the invocation list.
            int ValueReturnedByDelegate = delAp3();

            Console.WriteLine("Returned Value = {0}", ValueReturnedByDelegate);

            // Multicast delegate with an integer output parameter:
            SampleDelegate4 delAp4 = new SampleDelegate4(SampleMethodOne);

            delAp4 += SampleMethodTwo;


            // The ValueFromOutPutParameter will be 2, initialized by SampleMethodTwo(),
            // as it is the last method in the invocation list.
            int ValueFromOutPutParameter = -1;

            delAp4(out ValueFromOutPutParameter);
            Console.WriteLine("Returned Value = {0}", ValueFromOutPutParameter);
        }
Ejemplo n.º 2
0
        static void Main()
        {
            // ラムダ式によるデリゲート
            SampleDelegate3 d = n => - n;

            Console.WriteLine(d(3)); // 結果:-3

            // Action<int>は、戻り値のない引数ひとつの定義済み汎用デリゲート
            Action <int> disp = n => { Console.WriteLine(n); }; // 結果:123

            disp(123);

            // Func<string, int>は、戻り値と引数ひとつの定義済み汎用デリゲート
            Func <string, int> hex2int = str => Convert.ToInt32(str, 16);

            Console.WriteLine(hex2int("CD"));        // 出力値:205
        }