3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# 匿名メソッド

Posted at

古いソースコードによっては、ラムダ式で書かれておらず、まだC#2.0のデリゲートや匿名メソッドで記述されている事があるので、覚書の意味も込めて記載

samle
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    // デリゲートの宣言(C#2.0)
    delegate void SampleDeligate(string value);

    class Sample
    {
        public void Hello(string value)
        {
            Console.WriteLine(value);
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            Sample sample = new Sample();
            Console.WriteLine("挨拶文を入力して下さい。");
            string hello = Console.ReadLine();

            // C#2.0でのデリゲート利用
            SampleDeligate sampleDeligate = new SampleDeligate(sample.Hello);
            sampleDeligate(hello);

            // 匿名メソッド
            SampleDeligate sampleDeligate2 = delegate(string value)
            {
                Console.WriteLine(value);
            };
            sampleDeligate2(hello);

        }
    }
}

匿名メソッドを利用することで、デリゲートで使用していたHelloメソッドが不要になる!

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?