Visual Studio 2013 です。
下記コードを実行すると、ForEach2 はコンソールに出力するのですが、ForEach による出力がありません。どちらも同じ結果になると思っていたので、驚きました。これは仕様なのでしょうか? それともうちの環境で不具合が起こっているのでしょうか? 仕様とすればどういう仕様なのでしょう?
ブレークポイントを設定してみたところ、そもそも ForEach の中に入っていかないようなのです。
C#
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Threading.Tasks; 6 7namespace ConsoleApplication1 8{ 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 var array = new[] { 1, 2, 3 }; 14 Console.WriteLine("ForEach"); 15 array.ForEach(a => Console.WriteLine(a)); 16 Console.WriteLine("ForEach2"); 17 array.ForEach2(a => Console.WriteLine(a)); 18 Console.ReadKey(); 19 } 20 } 21 22 static class Extension 23 { 24 public static IEnumerable<T> ForEach<T>(this IEnumerable<T> target, Action<T> action) 25 { 26 foreach (var item in target) 27 { 28 action(item); 29 yield return item; 30 } 31 } 32 33 public static void ForEach2<T>(this IEnumerable<T> target, Action<T> action) 34 { 35 foreach (var item in target) 36 { 37 action(item); 38 } 39 } 40 } 41}
追記
次のようにすると、配列の中身が二回出力されました。
最適化が怪しい気がします。
C#
1Console.WriteLine("ForEach"); 2array.ForEach(a => Console.WriteLine(a)).ForEach2(a => Console.WriteLine(a));
追記
ForEach に [MethodImpl(MethodImplOptions.NoOptimization)] をつけて最適化を抑制してみましたが、結果は同じでした。さらに、もともと最適化オプションは外してコンパイルしています。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/20 09:35