LoginSignup
7
7

More than 5 years have passed since last update.

非ジェネリック型で渡されたリスト等の要素型を取得する

Posted at

非ジェネリック型の IEnumerable を引数として受けざるを得ない時、でも要素の型が何であるか知りたい場合に使う方法です。
(IEnumerable<> を実装していることが前提ですが。)

下のような方法では本当にシーケンス全体の要素がその型である保証がありませんよね。

seq.First().GetType()

そこで、Type クラスの GetGenericTypeDefinition メソッドと GetGenericArguments メソッドを使って以下のようなメソッドを作成します。

public static Type GetElementType(this IEnumerable seq)
{
    var typeOfSeq = seq
        .GetType()
        .GetInterfaces()
        .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>));

    return (typeOfSeq != null)
        ? typeOfSeq.GetGenericArguments()[0]
        : null;
}

これによって、IEnumerable<> の型引数を取得することが出来ました。
使いどころがどれだけあるかはさておき(笑)

7
7
0

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