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());
}
}
}
}
実行結果

-
前の記事
Ruby 文字列を1文字ずつに分割する 2021.09.10
-
次の記事
php absで絶対値を求める 2021.09.10
コメントを書く