サンプル集  >  C#  >  匿名メソッド
匿名メソッド
2015/12/28

「匿名メソッド」とは名前の無いメソッドのことのようです。

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

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

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

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: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

delegate void MyAction( string msg );

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

            MyAction act = delegate( string msg )
            {
                // 匿名メソッドの処理
                Console.WriteLine( msg );

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

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

実行します。

> Tokumei.exe
Hello! World
Main message!!

▲ PageTop  ■ Home


Copyright (C) 2015 ymlib.com