C# 拡張メソッドを作成する

  • 作成日 2021.09.10
  • 更新日 2022.04.09
  • C#
C# 拡張メソッドを作成する

C#で、拡張メソッドを作成するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • .net core 3.1
  • Microsoft Visual Studio Community 2019 Version 16.7.1

拡張メソッドを作成

拡張メソッドを作成するには、staticクラスにstaticメソッドを作成して、第一引数にthisを使用します。

以下は、拡張メソッドを使用して、リストの値をすべて2倍するだけのコードとなります。

using System;
using System.Collections.Generic;
using System.Linq;

namespace testapp
{

    static class ex
    {
        public static IEnumerable<int> times(this IEnumerable<int> list)
        {
            foreach (var x in list)
            {
                yield return x * 2;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                IEnumerable<int> num = new int[] { 1, 2, 3, 4, 5 };

                foreach (var x in num.times())
                {
                    Console.WriteLine(x);   // 2,4,6,8,10
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
        }
    }
}

実行結果