LoginSignup
0
2

More than 5 years have passed since last update.

C#のforeachの仕組み(6) decompileにおけるforとの比較 int[]編

Last updated at Posted at 2017-11-27

C#のforeachの仕組み(5) ILにおけるforとの比較 int[]編 の続きです。

概要

前回 、int[]のforeachをilでみたところ、
foreachしていませんでした。
ILSpyでDecompile結果を比較してみます。

※ILSpyの参考URL http://www.atmarkit.co.jp/fdotnet/dotnettips/1055ilspy/ilspy.html

コードとDecompile結果

forのコード。

Implement_array_for
using System;

namespace ConsoleAppArrayFor
{
    class Program
    {
        static void Main()
        {
            int[] numbers = { 0, 1, 2, 3, 4, 5, 6 };

            for (int i = 0; i < numbers.Length; i++)
            {
                Console.WriteLine(numbers[i]);
            }
        }
    }
}

forのDecompile by ILSpy。

Decompile_array_for
// ConsoleAppArrayFor.Program
private static void Main()
{
    int[] array = new int[]
    {
        0,
        1,
        2,
        3,
        4,
        5,
        6
    };
    for (int i = 0; i < array.Length; i++)
    {
        Console.WriteLine(array[i]);
    }
}

foreachのコード。

Implement_array_foreach
using System;

namespace ConsoleAppArrayFor
{
    class Program
    {
        static void Main()
        {
            int[] numbers = { 0, 1, 2, 3, 4, 5, 6 };

            foreach (var n in numbers)
            {
                Console.WriteLine(n);
            }
        }
    }
}

foreachのDecompile by ILSpy。

Decompile_array_foreach
// ConsoleAppArrayFor.Program
private static void Main()
{
    int[] array = new int[]
    {
        0,
        1,
        2,
        3,
        4,
        5,
        6
    };
    int[] array2 = array;
    for (int i = 0; i < array2.Length; i++)
    {
        int num = array2[i];
        Console.WriteLine(num);
    }
}

ILの相違点

diff_for_foreach_Decompile
@@ -11,9 +11,11 @@
        5,
        6
    };
-   for (int i = 0; i < array.Length; i++)
+   int[] array2 = array;
+   for (int i = 0; i < array2.Length; i++)
    {
-       Console.WriteLine(array[i]);
+       int num = array2[i];
+       Console.WriteLine(num);
    }
 }

まとめ

  • foreachはint[] array2の参照経由でforループしている?
  • Roslynがforeachを展開するロジックを調べてみたいです
  • list.ForEach()やArray.ForEachとも比較してみたいです

余談

dnSpyだと、foreachにDecompileされました。
monoベースとroslynベースの違いでしょうか。
foreachのDecompile by dnSpy。

Decompile_array_foreach_by_dnSpy
// ConsoleAppArrayFor.Program
// Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250
private static void Main()
{
    int[] numbers = new int[]
    {
        0,
        1,
        2,
        3,
        4,
        5,
        6
    };
    foreach (int i in numbers)
    {
        Console.WriteLine(i);
    }
}
0
2
2

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
0
2