LoginSignup
2
1

More than 5 years have passed since last update.

[C#] ジェネリックメソッド内でforeachを使いたい

Last updated at Posted at 2017-03-20

デバッグ用にいろんなリストをデバッグ出力できる一時関数を定義したかったのでやりかたメモ

TL;DR

そのままだと、 GetEnumerator が定義されていないとエラーになります。

image

対処として、where Type : IList で型引数に対する制約条件をつけてやると良いようです。
=> [追記] コメントにて IEnumerable<T> を使用したほうが汎用性が高いとのご指摘を頂きました。たしかにそうですね・・・。

サンプルコード

サンプルコード
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace hwapp
{
    class Hoge {
        public int i;
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Array
            int[] intArray = Enumerable.Range(0, 10).ToArray();
            PPrint(intArray);

            // List<int>
            List<int> intList = Enumerable.Range(0, 10).ToList();
            PPrint(intList);

            // List<T>
            List<Hoge> hogeList = Enumerable.Range(0, 10).Select(i => new Hoge { i = i * 10 }).ToList();
            PPrint(hogeList);
        }

        static void PPrint<Type> (Type T)
            where Type : IList
        {
            foreach (var obj in T)
            {
                if (obj is Hoge hoge) {
                    Console.WriteLine($"[{T.GetType()}] {hoge.i}");
                }
                else {
                    Console.WriteLine($"[{T.GetType()}] {obj}");
                }
            }
        }
    }
}
実行結果
[System.Int32[]] 0
[System.Int32[]] 1
[System.Int32[]] 2
[System.Int32[]] 3
[System.Int32[]] 4
[System.Int32[]] 5
[System.Int32[]] 6
[System.Int32[]] 7
[System.Int32[]] 8
[System.Int32[]] 9
[System.Collections.Generic.List`1[System.Int32]] 0
[System.Collections.Generic.List`1[System.Int32]] 1
[System.Collections.Generic.List`1[System.Int32]] 2
[System.Collections.Generic.List`1[System.Int32]] 3
[System.Collections.Generic.List`1[System.Int32]] 4
[System.Collections.Generic.List`1[System.Int32]] 5
[System.Collections.Generic.List`1[System.Int32]] 6
[System.Collections.Generic.List`1[System.Int32]] 7
[System.Collections.Generic.List`1[System.Int32]] 8
[System.Collections.Generic.List`1[System.Int32]] 9
[System.Collections.Generic.List`1[hwapp.Hoge]] 0
[System.Collections.Generic.List`1[hwapp.Hoge]] 10
[System.Collections.Generic.List`1[hwapp.Hoge]] 20
[System.Collections.Generic.List`1[hwapp.Hoge]] 30
[System.Collections.Generic.List`1[hwapp.Hoge]] 40
[System.Collections.Generic.List`1[hwapp.Hoge]] 50
[System.Collections.Generic.List`1[hwapp.Hoge]] 60
[System.Collections.Generic.List`1[hwapp.Hoge]] 70
[System.Collections.Generic.List`1[hwapp.Hoge]] 80
[System.Collections.Generic.List`1[hwapp.Hoge]] 90

参考

ジェネリック - C# によるプログラミング入門 | ++C++; // 未確認飛行 C
LINQのそのForEach、実はSelectで書き換えられるかも - Qiita
Type.GetType メソッド (String) (System)

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