ラムダ式 (C#)

C# 3.0 からラムダ式を導入しています。匿名メソッドよりも強力かつ柔軟に機能する仕組みです。

 

 

 

1. ラムダ式の基本

ラムダ式は、簡潔に関数オブジェクトを記述する機能です。
以下のように記述します。

( 入力パラメータ ) => { 式 または ステートメントブロック }

 

 

2. デリゲート型へ割り当てて実行

デリゲート型へラムダ式を割り当てる例を以下に記載します。

using System;

namespace lambda_test
{
    class Program
    {
        delegate int del(int i);

        static void Main(string[] args)
        {
            del myDelegate = x => x * x;
            int j = myDelegate(5);

            Console.WriteLine("result: " + j);
            Console.ReadLine();
        }
    }
}

3. 式ツリー型へ割り当てて実行

式ツリーのデータとしてラムダ式を割り当てる例を以下に示します。
この例は、 Compile メソッドを使用して、式ツリーを実行可能コードに戻す方法も合わせて示しています。
(注) Expression は .NET3.5 以降で使用可能です。

using System;
using System.Linq.Expressions;

namespace lambda_test
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int,int>> myET = x => x * x;
            Func<int, int> myDelegate2 = myET.Compile();
            int j = myDelegate2(5);

            Console.WriteLine("result: " + j);
            Console.ReadLine();
        }
    }
}

 

 

ライセンス

本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。

The MIT License (MIT)

Copyright © 2015-2022 Kinoshita Hidetoshi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

 

参考

 


 

変更履歴

2022-08-16 - ページデザイン更新
2015-06-09 - 新規作成

 

Programming Items トップページ

プライバシーポリシー