using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Foo {
public static Type GetEnumerableType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return type.GetGenericArguments()[0];
var iface = (from i in type.GetInterfaces()
where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)
select i).FirstOrDefault();
if (iface == null)
throw new ArgumentException("Does not represent an enumerable type.", "type");
return GetEnumerableType(iface);
}
static void Main() {
foreach (var type in new[] {
typeof(IEnumerable<string>),
typeof(List<int>),
typeof(EnumerableTest)
}) {
Console.WriteLine("{0}: {1}",
type.FullName,
GetEnumerableType(type).FullName);
}
}
}
class EnumerableTest : IEnumerable<long>, IEnumerable<double> {
IEnumerator<long> IEnumerable<long>.GetEnumerator() {
throw new NotImplementedException();
}
IEnumerator<double> IEnumerable<double>.GetEnumerator() {
throw new NotImplementedException();
}
public IEnumerator GetEnumerator() {
throw new NotImplementedException();
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uQ29sbGVjdGlvbnM7CnVzaW5nIFN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljOwp1c2luZyBTeXN0ZW0uTGlucTsKCmNsYXNzIEZvbyB7CglwdWJsaWMgc3RhdGljIFR5cGUgR2V0RW51bWVyYWJsZVR5cGUoVHlwZSB0eXBlKQoJewoJICAgIGlmICh0eXBlID09IG51bGwpCgkgICAgICAgIHRocm93IG5ldyBBcmd1bWVudE51bGxFeGNlcHRpb24oInR5cGUiKTsKCQoJICAgIGlmICh0eXBlLklzR2VuZXJpY1R5cGUgJiYgdHlwZS5HZXRHZW5lcmljVHlwZURlZmluaXRpb24oKSA9PSB0eXBlb2YoSUVudW1lcmFibGU8PikpCgkgICAgICAgIHJldHVybiB0eXBlLkdldEdlbmVyaWNBcmd1bWVudHMoKVswXTsKCQoJICAgIHZhciBpZmFjZSA9IChmcm9tIGkgaW4gdHlwZS5HZXRJbn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sZTxkb3VibGU+LkdldEVudW1lcmF0b3IoKSB7CiAgICAgICAgdGhyb3cgbmV3IE5vdEltcGxlbWVudGVkRXhjZXB0aW9uKCk7CiAgICB9CiAgICBwdWJsaWMgSUVudW1lcmF0b3IgR2V0RW51bWVyYXRvcigpIHsKICAgICAgICB0aHJvdyBuZXcgTm90SW1wbGVtZW50ZWRFeGNlcHRpb24oKTsKICAgIH0KfQ==
System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: System.String
System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: System.Int32
EnumerableTest: System.Int64