サンプル集  >  C#  >  ラムダ式
ラムダ式
2015/12/28

匿名メソッド の処理をラムダ式に書き直して見ます。

◆環境
OS Windows 7 Professional Service Pack 1 64bit
C# Microsoft Visual C# 2010 01018-587-4111284-70817

[ファイル]-[新規作成]-[プロジェクト]を選択。

[コンソール アプリケーション]を選択し、名前に「Lambda」と入力し「OK」。

書き直した箇所は、delegateの文です。

変更前:MyAction act = delegate( string msg )
変更後:MyAction act = ( msg )

delegateや引数の型stringが消えました。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

delegate void MyAction( string msg );

namespace Lambda
{
    class Program
    {
        static void Main( string[] args )
        {
            string main_msg = "Main message!!";

            // ラムダ式
            MyAction act = ( msg ) =>
            {
                // 匿名メソッドの処理
                Console.WriteLine( msg );

                // 匿名メソッドは上位スコープにアクセスできる
                Console.WriteLine( main_msg );
            };

            act( "Hello! World" );
        }
    }
}

実行します。

> Lambda.exe
Hello! World
Main message!!

▲ PageTop  ■ Home


Copyright (C) 2015 ymlib.com